标签:通过 for ftime orm mtime timezone strftime cno imp
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 <class ‘datetime.timedelta‘>
>>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 <class ‘datetime.datetime‘>
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() #获取总秒数
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
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
标签:通过 for ftime orm mtime timezone strftime cno imp
原文地址:https://www.cnblogs.com/zoer/p/13191711.html