python中datetime常用方法

时间:2022-06-06 23:08:33
# 可运算的时间方法包

>>> import datetime
>>> import time
>>> res = datetime.datetime.now() #获取当前格式化输出时间
>>> print(res)
2019-04-10 15:53:45.747720
>>> res + datetime.timedelta(days=-1) #datetime.timedelta的参数可以是days=,hours= 和其他时间表示
datetime.datetime(2019, 4, 9, 15, 53, 45, 747720)
>>> xx = res + datetime.timedelta(days = 365) #将当前时间和修改量相加,得到新的时间
>>> print(xx)
2020-04-09 15:53:45.747720
>>> yy = res + datetime.timedelta(hours = 4)
>>> print(yy)
2019-04-10 19:53:45.747720
>>> datetime.date.fromtimestamp(time.time())
datetime.date(2019, 4, 10)
>>> kk = datetime.date.fromtimestamp(time.time()) #将时间戳格式化日期
>>> print(kk)
2019-04-10
>>>

>>> f = datetime.datetime.now()   
>>> print(f)
2019-04-10 16:16:32.620877
>>> m = f.replace(month = 12) #类似于字符串的替换,不可修改原数据,替换后会产生新的值,参数可以为month=,year=,day=,hour=,minute=,second=..
>>> print(m)
2019-12-10 16:16:32.620877
>>>