Python模块---datetime
2021-05-05 19:29
标签:通过 for ftime orm mtime timezone strftime cno imp datetime.datetime.now() #获取本地时区当前时间对象 datetime.datetime(2020,11,11) #构建时间对象 时间对象的方法 strptime() #类方法,返回datetime时间对象 strftime() #时间对象方法,返回字符串,将时间对象格式化为字符串时间 datetime2 = datetime1 + timedelta Python模块---datetime 标签:通过 for ftime orm mtime timezone strftime cno imp 原文地址:https://www.cnblogs.com/zoer/p/13191711.htmldatetime
时间获取与转换
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
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()) #中国星期天
时间格式化
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
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
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
下一篇:java-多线程
文章标题:Python模块---datetime
文章链接:http://soscw.com/index.php/essay/82875.html