日期时间
from datetime import datetime, timedelta, timezone
now = datetime.now()
print(now) # 2024-02-02 14:27:12.247121
dt = datetime(2023, 12, 31, 12, 30, 00)
print(dt) # 2023-12-31 12:30:00
# 时间戳,和时区无关
ts = dt.timestamp()
print(ts) # 1703997000.0
# 本地时间
dt = datetime.fromtimestamp(ts)
print(dt) # 2023-12-31 12:30:00
# 字符串转换为日期时间
dt = datetime.strptime("2023-2-28 2:30:0", "%Y-%m-%d %H:%M:%S")
print(dt) # 2023-02-28 02:30:00
# 日期时间转换为字符串
str = datetime.strftime(now, "%Y-%m-%d %H:%M:%S")
print(str) # 2024-02-02 14:27:12
日期时间加减
# 日期时间加减
dt = dt + timedelta(days=1, hours=23)
print(dt) # 2023-03-02 01:30:00
dt = dt - timedelta(days=1)
print(dt) # 2023-03-01 01:30:00
时区转换
# 时区转换
bj_dt = dt.replace(tzinfo=timezone(timedelta(hours=8))) # 强制设置时区为UTC+00:00
print(bj_dt) # 2023-03-01 01:30:00+08:00
utc_dt = dt.replace(tzinfo=timezone.utc) # 强制设置时区为UTC+08:00
print(utc_dt) # 2023-03-01 01:30:00+00:00
bj_dt = bj_dt.astimezone(timezone(timedelta(hours=9))) # 转换时区为东9区时间
print(bj_dt) # 2023-03-01 02:30:00+09:00
bj_dt2 = utc_dt.astimezone(timezone(timedelta(hours=8))) # 转换时区为北京时间
print(bj_dt2) # 2023-03-01 09:30:00+08:00
标签:常用,30,00,datetime,2023,print,dt,python3 From: https://www.cnblogs.com/caroline2016/p/18454543