当前位置 : 主页 > 编程语言 > python >

Python datatime模块(学习笔记)

来源:互联网 收集:自由互联 发布时间:2022-06-18
获取当前时间 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 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

获取前n天/后n天(明天) timedelta

import datetime
times = datetime.date.today() + datetime.timedelta(days=1)
print(times)

执行结果为

2018-07-02

获取当天的开始时间和结束时间

import datetime
start = 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:00
2018-07-01 23:59:59.999999

获取两个datetime的时间差

import datetime
time =(datetime.datetime(2018,7,2,12,0,0) - datetime.datetime.now()).total_seconds()
print(time)

执行结果为(秒为单位)

73068.345855

时间关系转换

datetime -> string

import datetime
result = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(result)

运行结果为

2018-07-01 15:50:42

datetime -> timetuple

import datetime
result = 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 datetime
import time
now = datetime.datetime.now()
timestamp = time.mktime(now.timetuple())
print(timestamp)

运行结果为

1530431829.0

timestamp -> datetime


import datetime
timestamp = datetime.datetime.fromtimestamp(1421077403.0)
print(timestamp)

运行结果为

2015-01-12 23:43:23





网友评论