» Python快速入门 » 4. 常用模块篇 » 4.2 datetime 日期

datetime 日期

datetime 模块提供操作日期、时间的各种类。

获取当前日期

from datetime import datetime

print(datetime.now()) # YYYY-mm-DD HH:MM:SS.023000

# with spcific timezone
import pytz

tz = pytz.timezone("America/New_York")
print(datetime.now(tz)) # YYYY-mm-DD HH:MM:SS.023000

格式化日期

from datetime import datetime

nw = datetime.utcfromtimestamp(1629489987.567)
print(nw)
print(nw.strftime('Weekday long version  : %A'))
print(nw.strftime('Weekday short version : %a'))
print(nw.strftime('Weekday as a number   : %w'))
print(nw.strftime('Month long version    : %b'))
print(nw.strftime('Month short version.  : %d'))
print(nw.strftime('Month as a number     : %m'))
print(nw.strftime('Year long version     : %Y'))
print(nw.strftime('Year short version    : %y'))
print(nw.strftime('Day of the month      : %d'))
print(nw.strftime('Hour (24Hrs)          : %H'))
print(nw.strftime('Hour (12Hrs)          : %I'))
print(nw.strftime('AM / PM               : %p'))
print(nw.strftime('Minute                : %M'))
print(nw.strftime('Second                : %S'))
print(nw.strftime('%a %d-%m-%Y'))
print(nw.strftime('%a %m/%d/%Y'))
print(nw.strftime('%a %d/%m/%y'))
print(nw.strftime('%A %m-%d-%Y, %H:%M:%S'))
print(nw.strftime('%X %x'))

输出如下所示:

2021-08-20 20:06:27.567000
Weekday long version  : Friday
Weekday short version : Fri
Weekday as a number   : 5
Month long version    : Aug
Month short version.  : 20
Month as a number     : 08
Year long version     : 2021
Year short version    : 21
Day of the month      : 20
Hour (24Hrs)          : 20
Hour (12Hrs)          : 08
AM / PM               : PM
Minute                : 06
Second                : 27
Fri 20-08-2021
Fri 08/20/2021
Fri 20/08/21
Friday 08-20-2021, 20:06:27
20:06:27 08/20/21

字符串转化成日期

from datetime import datetime

dt = datetime.fromisoformat("2017-05-20 10:26:45")
print(dt) # 2017-05-20 10:26:45
print(nw.strftime('%a %m/%d/%Y')) # Fri 08/20/2021
print(nw.strftime('%A %m-%d-%Y, %H:%M:%S')) # Friday 08-20-2021, 20:06:27

from datetime import time
t = time.fromisoformat("15:58:21")
print(t.strftime('%I:%M %p')) # 03:58 PM

时间间隔

timedelta 表示时间段,两个时间点的差值。

from datetime import timedelta

delta = timedelta(
    days=50,
    seconds=27,
    microseconds=10,
    milliseconds=29000,
    minutes=5,
    hours=8,
    weeks=2
)
# Only days, seconds, and microseconds remain
print(repr(delta)) # datetime.timedelta(days=64, seconds=29156, microseconds=10)
print(delta) # 64 days, 8:05:56.000010

代码挑战

尝试修改编辑器中代码,使其打印 {'days': 2, 'hours': 3, 'minutes': 30, 'seconds': 0}

Loading...
> 此处输出代码运行结果
上页
下页