Python之datetime模块的使用
datetime模块的作用
datetime模块包含一些函数和类,用户完成日期和时间的解析、格式化和算术运算等。
1、自定义时,分,秒,毫秒,时区参数实例一个time对象的示例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime t = datetime.time(1, 2, 3) print(t) print('hour :', t.hour) print('minute :', t.minute) print('second :', t.second) print('microsecond:', t.microsecond) print('tzinfo :', t.tzinfo)
运行效果
01:02:03 hour : 1 minute : 2 second : 3 microsecond: 0 tzinfo : None
2、打印时间最大值和最小值
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime print('时间最小值 :', datetime.time.min) print('时间最大值 :', datetime.time.max) print('时间最小值微秒级别 :', datetime.time.resolution)
运行效果
时间最小值 : 00:00:00 时间最大值 : 23:59:59.999999 时间最小值微秒级别 : 0:00:00.000001
3、利用datetime模块获取当前的年,月,日
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime today = datetime.date.today() print('今天时间:', today) print('ordinal:', today.toordinal()) print('Year :', today.year) print('Mon :', today.month) print('Day :', today.day) print('ctime :', today.ctime()) tt = today.timetuple() print('tuple : tm_year =', tt.tm_year) print(' tm_mon =', tt.tm_mon) print(' tm_mday =', tt.tm_mday) print(' tm_hour =', tt.tm_hour) print(' tm_min =', tt.tm_min) print(' tm_sec =', tt.tm_sec) print(' tm_wday =', tt.tm_wday) print(' tm_yday =', tt.tm_yday) print(' tm_isdst =', tt.tm_isdst)
运行效果
今天时间: 2020-05-20 ordinal: 737565 Year : 2020 Mon : 5 Day : 20 ctime : Wed May 20 00:00:00 2020 tuple : tm_year = 2020 tm_mon = 5 tm_mday = 20 tm_hour = 0 tm_min = 0 tm_sec = 0 tm_wday = 2 tm_yday = 141 tm_isdst = -1
4、天数每天加1和格式化时间戳的示例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime import time o = 733478 print('o :', o) print('fromordinal(o) :', datetime.date.fromordinal(o)) t = time.time() print('t :', t) print('fromtimestamp(t):', datetime.date.fromtimestamp(t))
运行效果
o : 733478 fromordinal(o) : 2009-03-12 t : 1589960551.3368747 fromtimestamp(t): 2020-05-20
5、打印日期的最大值,最小值的示例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime print('日期最小值 :', datetime.date.min) print('日期最大值 :', datetime.date.max) print('精确到时分秒 :', datetime.date.resolution)
运行效果
日期最小值 : 0001-01-01 日期最大值 : 9999-12-31 精确到时分秒 : 1 day, 0:00:00
6、日期时间的替换
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime d1 = datetime.date(2008, 3, 29) print('d1:', d1.ctime()) d2 = d1.replace(year=2009) print('d2:', d2.ctime())
运行效果
d1: Sat Mar 29 00:00:00 2008
d2: Sun Mar 29 00:00:00 2009
7、生成日期时间可算术运算的对象
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime print('microseconds:', datetime.timedelta(microseconds=1)) print('milliseconds:', datetime.timedelta(milliseconds=1)) print('seconds :', datetime.timedelta(seconds=1)) print('minutes :', datetime.timedelta(minutes=1)) print('hours :', datetime.timedelta(hours=1)) print('days :', datetime.timedelta(days=1)) print('weeks :', datetime.timedelta(weeks=1))
运行效果
microseconds: 0:00:00.000001 milliseconds: 0:00:00.001000 seconds : 0:00:01 minutes : 0:01:00 hours : 1:00:00 days : 1 day, 0:00:00 weeks : 7 days, 0:00:00
8、获取指定时间段的秒数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime for delta in [datetime.timedelta(microseconds=1), datetime.timedelta(milliseconds=1), datetime.timedelta(seconds=1), datetime.timedelta(minutes=1), datetime.timedelta(hours=1), datetime.timedelta(days=1), datetime.timedelta(weeks=1), ]: print('{:15} = {:8} seconds'.format( str(delta), delta.total_seconds()) )
运行效果
0:00:00.000001 = 1e-06 seconds 0:00:00.001000 = 0.001 seconds 0:00:01 = 1.0 seconds 0:01:00 = 60.0 seconds 1:00:00 = 3600.0 seconds 1 day, 0:00:00 = 86400.0 seconds 7 days, 0:00:00 = 604800.0 seconds
9、时间的算术运算
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime today = datetime.date.today() print('Today :', today) one_day = datetime.timedelta(days=1) print('One day :', one_day) yesterday = today - one_day print('Yesterday:', yesterday) tomorrow = today + one_day print('Tomorrow :', tomorrow) print() print('tomorrow - yesterday:', tomorrow - yesterday) print('yesterday - tomorrow:', yesterday - tomorrow)
运行效果
Today : 2020-05-20 One day : 1 day, 0:00:00 Yesterday: 2020-05-19 Tomorrow : 2020-05-21 tomorrow - yesterday: 2 days, 0:00:00 yesterday - tomorrow: -2 days, 0:00:00
10、时间的算术浮点运算
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime one_day = datetime.timedelta(days=1) print('1 day :', one_day) print('5 days :', one_day * 5) print('1.5 days :', one_day * 1.5) print('1/4 day :', one_day / 4) # assume an hour for lunch work_day = datetime.timedelta(hours=7) meeting_length = datetime.timedelta(hours=1) print('meetings per day :', work_day / meeting_length)
运行效果
1 day : 1 day, 0:00:00
5 days : 5 days, 0:00:00
1.5 days : 1 day, 12:00:00
1/4 day : 6:00:00
meetings per day : 7.0
11、时间和日期的比较
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime import time print('Times:') t1 = datetime.time(12, 55, 0) print(' t1:', t1) t2 = datetime.time(13, 5, 0) print(' t2:', t2) print(' t1 < t2:', t1 < t2) print() print('Dates:') d1 = datetime.date.today() print(' d1:', d1) d2 = datetime.date.today() + datetime.timedelta(days=1) print(' d2:', d2) print(' d1 > d2:', d1 > d2)
运行效果
Times: t1: 12:55:00 t2: 13:05:00 t1 < t2: True Dates: d1: 2020-05-21 d2: 2020-05-22 d1 > d2: False
12、通过反射获取年,月,日,时,分,秒的示例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime print('Now :', datetime.datetime.now()) print('Today :', datetime.datetime.today()) print('UTC Now:', datetime.datetime.utcnow()) print() FIELDS = [ 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond', ] d = datetime.datetime.now() for attr in FIELDS: print('{:15}: {}'.format(attr, getattr(d, attr)))
运行效果
Now : 2020-05-21 09:43:57.311893 Today : 2020-05-21 09:43:57.311894 UTC Now: 2020-05-21 01:43:57.311893 year : 2020 month : 5 day : 21 hour : 9 minute : 43 second : 57 microsecond : 311893
13、时间和日期的拼接示例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import datetime 2 3 t = datetime.time(1, 2, 3) 4 print('t :', t) 5 6 d = datetime.date.today() 7 print('d :', d) 8 9 dt = datetime.datetime.combine(d, t) 10 print('dt:', dt)
运行效果
t : 01:02:03 d : 2020-05-21 dt: 2020-05-21 01:02:03
14、日期时间的格式化
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime format = "%Y-%m-%d %H:%M:%S" today = datetime.datetime.today() print('ISO :', today) s = today.strftime(format) print('strftime:', s) d = datetime.datetime.strptime(s, format) print('strptime:', d.strftime(format))
运行效果
ISO : 2020-05-21 09:50:46.448841 strftime: 2020-05-21 09:50:46 strptime: 2020-05-21 09:50:46
15、格式化的介绍
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime today = datetime.datetime.today() print('ISO :', today) print('format(): {:%Y-%m-%d %H:%M:%S}'.format(today))
运行效果
ISO : 2020-05-21 10:02:14.044698
format(): 2020-05-21 10:02:14
符号 | 注释 | 示例 |
---|---|---|
%a |
缩写的星期几 | 'Wed' |
%A |
完整的星期几 | 'Wednesday' |
%w |
星期几的编号:0(星期天)到6(星期六) | '3' |
%d |
当月哪一天 | '13' |
%b |
缩写的月份名 | 'Jan' |
%B |
完整的月份名 | 'January' |
%m |
当年哪个月 | '01' |
%y |
不加世纪编号的年份 | '16' |
%Y |
加世纪编号的年份 | '2016' |
%H |
24小时制的小时数 | '17' |
%I |
12小时制的小时数 | '05' |
%p |
AM/PM | 'PM' |
%M |
分钟 | '00' |
%S |
秒 | '00' |
%f |
微秒 | '000000' |
%z |
区分时区的日期时间对象的UTC偏移 | '-0500' |
%Z |
时区名 | 'EST' |
%j |
当年的哪一天 | '013' |
%W |
当年的哪一周 | '02' |
%c |
当前本地化环境的日期和时间表示 | 'Wed Jan 13 17:00:00 2016' |
%x |
当前本地化环境的日期表示 | '01/13/16' |
%X |
当前本地化环境的时间表示 | '17:00:00' |
%% |
字面量%字符 | '%' |
16、时区的自动转换示例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime min6 = datetime.timezone(datetime.timedelta(hours=-6)) plus6 = datetime.timezone(datetime.timedelta(hours=6)) d = datetime.datetime.now(min6) print(min6, ':', d) print(datetime.timezone.utc, ':', d.astimezone(datetime.timezone.utc)) print(plus6, ':', d.astimezone(plus6)) # 转换为当前系统时区 d_system = d.astimezone() print(d_system.tzinfo, ' :', d_system)
运行效果
UTC-06:00 : 2020-05-20 20:15:04.716839-06:00 UTC : 2020-05-21 02:15:04.716839+00:00 UTC+06:00 : 2020-05-21 08:15:04.716839+06:00 EST : 2020-05-21 10:15:04.716839+08:00
17、时间戳转时间的示例
import datetime ts = 1590017732 ret = datetime.datetime.fromtimestamp(ts) print(ret)
运行效果
2020-05-21 07:35:32
18、时间转时间戳的示例
import datetime d = '2020-05-21 07:35:32' ret = datetime.datetime.fromisoformat(d).timestamp() print(ret)
运行效果
1590017732.0