如何将日期字符串转换为指定时区的日期时间对象

How to convert date string to a datetime object in a specified timezone

我可以使用以下方法将 YYYY-MM-DD 格式的给定日期字符串转换为 datetime 对象:

from datetime import datetime
dt = datetime.strptime(date_str, '%Y-%m-%d')

但是,这默认使用当前机器的时区。

有没有办法在转换中指定特定的时区(如UTC、PST等),以便获得的datetime对象在该时区。

我正尝试在 Python 3.4.3.

中执行此操作

仅使用 Python 的标准库是不可能的。

为了充分的灵活性,安装 python-dateutilpytz 以及 运行:

date_str = '2015-01-01'
dt = pytz.timezone('Europe/London').localize(dateutil.parser.parse(date_str))

这会为您提供 Europe/London 时区的日期时间。

如果你只需要解析 '%Y-%m-%d' 个字符串那么你只需要 pytz:

from datetime import datetime
naive_dt = datetime.strptime(date_str, '%Y-%m-%d')
dt = pytz.timezone('Europe/London').localize(naive_dt)