在python中,如何从日期和时间创建可识别时区的datetime? [英] In python, how do I create a timezone aware datetime from a date and time?
问题描述
在Python中,假设我的日期为2016年12月25日。如何在该日期创建一个可识别时区的中午日期时间?
In Python, let's say I have a date of 25 December 2016. How can I create a timezone-aware datetime of noon on that date?
奖励积分是否
推荐答案
诀窍是先
The trick is to first combine
the naive time and the date into a naive datetime. This naive datetime can then be converted to an aware datetime.
可以使用第三方软件包 pytz
(在这种情况下,使用欧洲/伦敦时区):
The conversion can be done using the third party package pytz
(using, in this case, the 'Europe/London' timezone):
import datetime
import pytz
naive_time = datetime.time(0, 30)
date = datetime.date(2016, 12, 25)
naive_datetime = datetime.datetime.combine(date, naive_time)
timezone = pytz.timezone('Europe/London')
aware_datetime = timezone.localize(naive_datetime)
如果您在Django中进行操作,并且想使用当前时区(在Django中配置),则可以用对的调用来替换最后两行make_aware
:
If you're doing it in Django, and want to use the current timezone (as configured in Django), you can replace the final two lines with a call to make_aware
:
from django.utils import timezone
aware_datetime = timezone.make_aware(naive_datetime)
这篇关于在python中,如何从日期和时间创建可识别时区的datetime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!