Python 日期和时间

老规矩,先上官方文档链接:dateime 以及 格式化说明

from datetime import datetime

now = datetime.now()
print(now)
print(f"{now:%Y-%m-%d %H:%M:%S.%f}")
print(now.date())
print(now.time())

# 时间戳是 float 类型的秒数
#print(dir(now.timestamp()))
ts_sec = now.timestamp().real
print(ts_sec)
# 转成毫秒数表示的时间戳
ts_ms = int(ts_sec * 1000)
print(ts_ms)
# 时间戳转 datetime
print(datetime.fromtimestamp(ts_sec))

year = now.date().year
month = now.date().month
day = now.date().day
hour = now.time().hour
minute = now.time().minute
second = now.time().second
microsecond = now.time().microsecond
s = f"{year}-{month:02d}-{day:02d} {hour:02d}:{minute:02d}:{second:02d}.{microsecond:06d}"
print(s)
# 字符串日期转 datetime
print(datetime.fromisoformat(s))

你可能感兴趣的:(Python,python)