首页 > 解决方案 > 如何正确格式化时间戳

问题描述

我有以下数据库中的时间戳信息:

time_format: str = "%d/%b/%Y %H:%M %Z"
timestamp = '2020-11-03T21:32:19.722012+00:00' 
timezone = 'America/New_York'

如何使用 datetime 将此信息格式化为如下所示:

11/03/2020 17:32EST

我能够做到这一点:

datetime.datetime.now().fromisoformat(timestamp_utc).strftime(time_format)

但无法弄清楚如何用任何时间替换 datetime.now() 然后显示所需的时区代替“UTC”

标签: python

解决方案


由于 python 没有开箱即用的出色时区支持,因此我建议将此pytz库用于此用例。

from datetime import datetime
import pytz

# Input
datetime_str = '2020-11-03T21:32:19.722012+00:00'
timezone_str = 'America/New_York'
output_format = '%m/%d/%Y %H:%M %Z'

# Convert input datetime str to python datetime obj
# this datetime is timezone aware, with tz=UTC
utc_datetime = datetime.fromisoformat(datetime_str)

# Convert input timezone str to a pytz timezone object
new_timezone = pytz.timezone(timezone_str)

# Adjust the UTC datetime to use the new timezone
new_timezone_datetime = utc_datetime.astimezone(new_timezone)

# Print in the desired output format
print(new_timezone_datetime.strftime(output_format))

如果我运行上面的代码,我会得到以下...

11/03/2020 16:32 EST

编辑:16:32代替的原因17:32是因为American/New_York与 相同US/Eastern,因为它们在一年中的不同时间点使用EST/ EDT(夏令时)。2020-11-03碰巧掉进去了EST


推荐阅读