Python模块---datetime

2021-05-05 19:29

阅读:489

标签:通过   for   ftime   orm   mtime   timezone   strftime   cno   imp   

datetime

时间获取与转换

datetime.datetime.now() #获取本地时区当前时间对象
datetime.datetime.utcnow() #GMT 零时区当前时间对象
datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=6))) #获取对应时区的当前时间对象
时间相减可获取到datetime.timedelta类型的时间差对象

import datetime,math,time
m = datetime.datetime.now()
time.sleep(2)
n = datetime.datetime.now()
print(n-m,type(n-m))
now = (n-m).total_seconds()  #total_seconds()获取相差总秒数	
print(math.ceil(now))
>>0:00:02.000115 
>>3

datetime.datetime(2020,11,11) #构建时间对象

t1 = datetime.datetime.now()
t1.timestamp() #获取时间戳对象,无论是本地时间还是UTC时间,时间戳永远是一样的
datetime.datetime.fromtimestamp(t1.timestamp()) #通过时间戳对象获取时间对象,返回本地时间对象

时间对象的方法

d = datetime.datetime.now()
print(d.date())
print(d.time())
print(d.year)
print(d.month)
print(d.day)
print(d.hour)
print(d.minute)
print(d.second)
print(d.microsecond)
print(d.weekday()) #老外星期天
print(d.isoweekday())  #中国星期天

时间格式化

strptime() #类方法,返回datetime时间对象

datestr = ‘1111-11-11 11:11:11‘
d = datetime.datetime.strptime(datestr,"%Y-%m-%d %H:%M:%S")
print(d,type(d))
>>1111-11-11 11:11:11 

strftime() #时间对象方法,返回字符串,将时间对象格式化为字符串时间
format函数时间格式化为字符串

d = datetime.datetime.now()
print(d,type(d))
print(d.strftime(‘%Y/%m/%d %H:%M:%S‘))
>>2020/06/25 11:49:42
print("{:%Y/%m/%d %H:%M:%S}".format(d))
>>2020/06/25 11:49:42

时间加减

datetime2 = datetime1 + timedelta
datetime2 = datetime1 - timedelta
timedelta = datetime1 - datetime2
timedelta.total_seconds() #获取总秒数

时间相加 加delta时间
d = datetime.datetime.now()
y = d + datetime.timedelta(days=1)
print(d,y)
>2020-06-25 12:07:44.463991 2020-06-26 12:07:44.463991
时间相减 可以减delta与datetime
d = datetime.datetime.now()
y = d - datetime.timedelta(days=1)
print(d,y)
2020-06-25 12:09:06.757698 2020-06-24 12:09:06.757698

Python模块---datetime

标签:通过   for   ftime   orm   mtime   timezone   strftime   cno   imp   

原文地址:https://www.cnblogs.com/zoer/p/13191711.html


评论


亲,登录后才可以留言!