import datetime
dt = datetime.datetime(year=2020, month=6, day=25, hour=11, minute=51, second=49)
s = dt.strftime("'%Y/%m/%d %H:%M:%S")
print(s) # '2020/06/25 11:51:49
s = dt.strftime('%d %B, %Y, %A')
print(s) # 25 June, 2020, Thursday
将给定日期转换为 “mmm-dd, YYYY” 的格式
import datetime
d1 = datetime.date(2010, 9, 28)
print(d1.strftime('%b-%d,%Y'))
# Sep-28,2010
在 python 中将字符串解析为 datetime对象
from dateutil import parser
s = '2020-06-25'
dt = parser.parse(s)
print(dt) # 2020-06-25 00:00:00
print(type(dt)) #
s = 'March 31, 2010, 10:51pm'
dt = parser.parse(s)
print(dt) # 2010-03-31 22:51:00
print(type(dt)) #
将字符串日期解析为 datetime 对象
from dateutil import parser
s1 = "2010 Jan 1"
s2 = '31-1-2000'
s3 = 'October10, 1996, 10:40pm'
dt1 = parser.parse(s1)
dt2 = parser.parse(s2)
dt3 = parser.parse(s3)
print(dt1) # 2010-01-01 00:00:00
print(dt2) # 2000-01-31 00:00:00
print(dt3) # 1996-10-10 22:40:00
计算以下列表中连续的天数
import numpy as np
from dateutil import parser
dateString = ['Oct, 2, 1869', 'Oct, 10, 1869', 'Oct, 15, 1869', 'Oct, 20, 1869', 'Oct, 23, 1869']
dates = [parser.parse(i) for i in dateString]
td = np.diff(dates)
print(td)
# [datetime.timedelta(days=8) datetime.timedelta(days=5)
# datetime.timedelta(days=5) datetime.timedelta(days=3)]
d = [i.days for i in td]
print(d) # [8, 5, 5, 3]
统计两个日期之间有多少个星期六
import datetime
d1 = datetime.date(1869, 1, 2)
d2 = datetime.date(1869, 10, 2)
dt = (d2 - d1).days
print(dt)
print(d1.isoweekday()) # 6
print(dt // 7 + 1) # 40