更改日期对象 Python 的时区 [英] Change Timezone for Date object Python
问题描述
您好,我正在使用 Pythonanywhere 并且当我打电话时
from datetime import *打印 date.today().day
它打印的日期与我居住的地方(德克萨斯州奥斯汀)不同.我认为这是因为存在时区差异.我如何告诉日期对象我住在哪里,以便它获得正确的时区.提前致谢
最可靠的方法是使用 pytz
.您可以使用 pip install pytz
简单地安装它.
要使用 pytz
获取本地日期,您可以简单地执行此操作(注意 date.today
方法不会采用时区):
将其与当前格林威治日期进行比较:
<预><代码>>>>greenwich_date = datetime.now(pytz.timezone('Etc/Greenwich'))>>>greenwich_date.date()datetime.date(2014, 12, 1)Hello I am using Pythonanywhere and when I call
from datetime import *
print date.today().day
It is printing a different day than the day it is where I live (Austin, Texas). I figured it is because there is a timezone difference. How would I tell the date object where I live so it gets the right timezone. Thanks in advance
The most robust way to do this is to use pytz
. You can install it simply with pip install pytz
.
To get the local date with pytz
, you can simply do this (note that the date.today
method will not take a timezone):
>>> from datetime import datetime
>>> import pytz
>>> local_date = datetime.now(pytz.timezone('US/Central')) # use datetime here
>>> local_date.date() # now call date method
datetime.date(2014, 11, 30)
Compare that to the present Greenwich date:
>>> greenwich_date = datetime.now(pytz.timezone('Etc/Greenwich'))
>>> greenwich_date.date()
datetime.date(2014, 12, 1)
这篇关于更改日期对象 Python 的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!