python datetime 模块

时间:2022-06-03 06:28:49

import datetime

datetime.datetime.now()  打印本地当前时间
>>> print(datetime.datetime.now())
2017-12-20 17:30:31.035954
时间戳直接转成日期格式
>>> print(datetime.date.fromtimestamp(time.time()))
2017-12-20
把当前时间以指定的日期格式打印出来
>>> print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
2017-12-20 17:33:44

datetime.timedelta()  时间加减
显示当前时间+3天时间
print(datetime.datetime.now() + datetime.timedelta(days=3))

2017-12-24 10:53:23.549693

显示当前时间 -3天时间

print(datetime.datetime.now() + datetime.timedelta(days=-3))

2017-12-18 10:53:23.549693
当前时间+3小时
print(datetime.datetime.now() + datetime.timedelta(hours=3))

2017-12-21 13:53:23.549693
当前时间+30分钟
print(datetime.datetime.now() + datetime.timedelta(minutes=30))

2017-12-21 11:23:23.549693
自定义时间
c_time = (datetime.datetime.now())
print(c_time.replace(year=2016,month=3,day=5,hour=5,minute=5,second=40)) 2016-03-05 05:05:40.549693