Datatime 时间模块

#获取当前的 年/月/日
today = datetime.date.today()
out:     2020-05-05

# 获取指定的年/月/日
t = datetime.date(1992,4,2)
out:    1992-04-02

 

# 获取当前本地时间的 年/月/日/ 时/分/秒
now =datetime.datetime.now()
out:  2020-05-05 19:10:59.833475

# 获取指定 的  年/月/日/ 时/分/秒
t1 = datetime.datetime(1989,2,9,11,43,30)
out:        1989-02-09 11:43:30
t2= datetime.datetime(1989,2,20,7,30,10)
# 时间间隔datedelta
print(t2-t1)
out:    10 days, 19:46:40

 

# 获取时间间隔(时间差),这里计算2000-10-1过了100天的日期
t1 = datetime.datetime(2000,10,1)
t2 = datetime.timedelta(100)
print(t1+t2)
out:     2001-01-09 00:00:00

 

# 字符串转换方法
from dateutil.parser import parse
# paer() 返回的是  <class 'datetime.datetime'>
date1 = '2017 6 1'
date2 ='30/12/2017' #2017年12月30日
date3 = '2000-1-1'
date4 = '5/9/2014' # 2014年5月9日
date5 = 'Jan 20, 1997 10:45PM' # 1997年1月20日 22点的45分0秒
print(parse(date1))
print(parse(date2))
print(parse(date3))
print(parse(date4,dayfirst=True)) #如果希望日在月份之前,可以通过dayfirst来设置
print(parse(date5))
out:       2017-06-01 00:00:00
2017-12-30 00:00:00 
2000-01-01 00:00:00
2014-09-05 00:00:00
1997-01-20 22:45:00

 

posted @ 2020-05-05 19:03  籽俊  阅读(178)  评论(0编辑  收藏  举报