Python 中的日期和时间

2022-07-04  本文已影响0人  Ritchie_Li

1. 将字符串转换为日期时间对象

import datetime

dt = datetime.datetime.strptime("2022-04-15T08:27:18-0500", "%Y-%m-%dT%H:%M:%S%z")

print(dt)

print(type(dt))

输出:

2022-04-15 08:27:18-05:00

<class 'datetime.datetime'>

2. 创建时区日期时间对象

from datetimeimport datetime, timedelta, timezone

JST = timezone(timedelta(hours=+8))

dt = datetime(2023, 1, 1, 12, 0, 0, tzinfo=JST)

print(dt)

# 2023-01-01 12:00:00+08:00

print(dt.tzname())

# UTC+08:00

dt = datetime(2023, 1, 1, 12, 0, 0, tzinfo=timezone(timedelta(hours=8), 'JST'))

print(dt.tzname)

# <built-in method tzname of datetime.datetime object at 0x000001A7E44ACE40>

有夏令时的区域, 使用dateutil 模块

from datetime import datetime

from dateutil import tz

local = tz.gettz()# Local time

PT = tz.gettz('US/Pacific')# Pacific time

dt_l = datetime(2023, 1, 1, 12, tzinfo=local)# I am in EST

dt_pst = datetime(2023, 1, 1, 12, tzinfo=PT)

dt_pdt = datetime(2023, 7, 1, 12, tzinfo=PT)# DST is handled automatically

print(dt_l)

# 2023-01-01 12:00:00+08:00

print(dt_pst)

# 2023-01-01 12:00:00-08:00

print(dt_pdt)

# 2023-07-01 12:00:00-07:00

3. 计算时间差

from datetimeimport datetime, timedelta

now = datetime.now()

then = datetime(2023, 5, 23)

delta = then - now

print(delta.days)

# 321

print(delta.seconds)

# 11055

上一篇下一篇

猜你喜欢

热点阅读