一、datetime
1、date
2、time
import datetime
datetime.MAXYEAR
datetime.MINYEAR
today = datetime.date.today()
today
today.year
today.month
today.day
today.weekday()
today.isoweekday()
9999
1
datetime.date(2019, 9, 7)
2019
9
7
5
6
3、datetime
- year
- month
- day
birthdate = datetime.date(2010, 3, 12)
birthdate.year
birthdate.day
t = datetime.time(15, 46, 32)
t.hour
t.minute
t.second
2010
12
15
46
32
import datetime
now = datetime.datetime.now()
now
now.year
now.second
now.microsecond #微秒
datetime.datetime(2019, 9, 7, 20, 14, 45, 543196)
2019
7
45
543196
4、格式转换
- 字符串到日期时间 datetime.datetime.strptime(‘txt’, ‘%Y-%m-%d’)
- 日期时间到字符串 datetime.datetime.strftime( ‘%Y/%m/%d’)
import datetime
s = '2018-2-23'
t = datetime.datetime.strptime(s, '%Y-%m-%d') #Y要大写
t
now = datetime.datetime.now()
now
txt = now.strftime('%Y/%m/%d')
txt
datetime.datetime(2018, 2, 23, 0, 0)
datetime.datetime(2019, 9, 7, 20, 19, 16, 226808)
'2019/09/07'
-
占位符
%Y 四位年份
%y 两位年份
%m 两位月份
%d 两位日期
%H 两位小时
%M 两位分钟
%S 两位秒数
%f 微秒
%w 星期-0-65、时间差 timedelta
import datetime
d = datetime.datetime(2018, 3, 5, 22, 44)
birthdate = datetime.datetime(2016, 5, 2, 19, 33, 44)
d - birthdate #相隔了672天11416秒
datetime.timedelta(days=672, seconds=11416)
- days
- seconds
- hours
diff = d - birthdate
diff.days
diff.seconds
diff.total_seconds() #实际相隔的秒数
672
11416
58072216.0
o = datetime.datetime(2008, 8, 8, 20, 8)
o + datetime.timedelta(days=100)
result = d + datetime.timedelta(days = -100)
result
d + datetime.timedelta(seconds=3000)
datetime.datetime(2008, 11, 16, 20, 8)
datetime.datetime(2017, 11, 25, 22, 44)
datetime.datetime(2018, 3, 5, 23, 34)