在使用python写调度任务的时候,离不开的必然有日期和时间的处理;最常见的有根据字符串生成时间、将时间生成指定格式的字符串、日期时间的计算(加减)等等。在python中对日期时间进行操作的包为datetime。下面就对该包的一些常用操作和对应的参数进行介绍。
常用方法
获取当前的日期时间
使用datetime获取当前日期时间的方法是datetime.datetime.now():
将日期时间与字符串之间的互转
将日期时间转换为字符串的方法是datetime.datetime.strftime():
上面的代码用来将当前时间转换为“年-月-日 时:分:秒”的格式。strftime方法接收两个参数:datetime对象和输出格式。对于输出格式中的各个参数的意义,请参考本节后面的表格。
将字符串转换为日期时间的方法是datetime.datetime.strptime():
上面的代码用来将字符串转换为datetime。strptime方法有两个参数:时间字符串和时间字符串的格式。对于格式的具体意义,参考本节后面的表格。
格式 | 意义 |
---|---|
%a | Abbreviated weekday name |
%A | Full weekday name |
%b | Abbreviated month name |
%B | Full month name |
%c | Date and time representation appropriate for locale |
%d | Day of month as decimal number |
%H | Hour in 24-hour format (00 - 23) |
%I | Hour in 12-hour format (01 - 12) |
%j | Day of year as decimal number (001 - 366) |
%m | Month as decimal number (01 - 12) |
%M | Minute as decimal number (00 - 59) |
%p | Current locale’s A.M./P.M. indicator for 12-hour clock |
%S | Second as decimal number (00 - 59) |
%U | Week of year as decimal number, with Sunday as first day of week (00 - 51) |
%w | Weekday as decimal number (0 - 6; Sunday is 0) |
%W | Week of year as decimal number, with Monday as first day of week (00 - 51) |
%x | Date representation for current locale |
%X | Time representation for current locale |
%y | Year without century, as decimal number (00 - 99) |
%Y | Year with century, as decimal number |
%z, %Z | Time-zone name or abbreviation; no characters if time zone is unknown |
日期时间的运算
计算两个时间之间的时间差
两个datetime之间可以直接进行减运算
通过上面的代码可以看到,两个datetime之间的减运算会得到一个datetime.timedelta对象,调用datetime.timedelta的相关属性则可以获取需要的差值信息。通过datetime.timedelta可以获取的时间查信息如下:
属性 | 意义 |
---|---|
days | datetime.timedelta用天数表示 |
seconds | datetime.timedelta用秒数表示 |
microseconds | datetime.timedelta用毫秒数表示 |
对已有的时间进行加减操作
对datetime的加减操作,也需要借助datetime.timedelta对象,对已有的datetime对象加上或减去datetime.timedelta对象,则获得一个新的datetime:
上面的代码在进行时间的减法操作之前也是先构建了一个datetime.timedelta对象,构建datetime.timedelta对象时,可以使用的参数如下:
属性 | 意义 |
---|---|
weeks | datetime.timedelta包含的周数 |
days | datetime.timedelta包含的天数 |
hours | datetime.timedelta包含的小时数 |
minutes | datetime.timedelta包含的分钟数 |
seconds | datetime.timedelta包含的秒数 |
microseconds | datetime.timedelta包含的毫秒数 |
使用实例
指定的格式输出当前时间
|
|
将给定的时间按照指定的格式输出
|
|
将给定的时间字符串转换为时间
|
|
列出两个日期之间的日期
|
|
将时间秒转换为时间对象
|
|