获取当前时间 datatime import datetime time = datetime.datetime.now() print(time) 执行结果为 2018-07-01 15:22:30.411582 获取当天日期 data import datetime times = datetime.date.today() print(times) 执行结果为 2018-07-01 获
获取当前时间 datatime
import datetimetime = datetime.datetime.now()
print(time)
执行结果为
2018-07-01 15:22:30.411582获取当天日期 data
import datetimetimes = datetime.date.today()
print(times)
执行结果为
2018-07-01获取前n天/后n天(明天) timedelta
import datetimetimes = datetime.date.today() + datetime.timedelta(days=1)
print(times)
执行结果为
2018-07-02获取当天的开始时间和结束时间
import datetimestart = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
end = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
print(start)
print(end)
执行结果为
2018-07-01 00:00:002018-07-01 23:59:59.999999
获取两个datetime的时间差
import datetimetime =(datetime.datetime(2018,7,2,12,0,0) - datetime.datetime.now()).total_seconds()
print(time)
执行结果为(秒为单位)
73068.345855时间关系转换
datetime -> string
import datetimeresult = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(result)
运行结果为
2018-07-01 15:50:42datetime -> timetuple
import datetimeresult = datetime.datetime.now().timetuple()
print(result)
运行结果为
time.struct_time(tm_year=2018, tm_mon=7, tm_mday=1, tm_hour=15, tm_min=52, tm_sec=45, tm_wday=6, tm_yday=182, tm_isdst=-1)datetime -> timestamp
import datetimeimport time
now = datetime.datetime.now()
timestamp = time.mktime(now.timetuple())
print(timestamp)
运行结果为
1530431829.0timestamp -> datetime
timestamp = datetime.datetime.fromtimestamp(1421077403.0)
print(timestamp)
运行结果为
2015-01-12 23:43:23