[英]How to, with python, take a UTC datetime, autodetect users timezone, and convert the datetime to desired format?
关于UTC日期时间转换有很多问题,似乎没有“最佳方式”的共识。
根据这个: http ://lucumr.pocoo.org/2011/7/15/eppur-si-muove/,pytz是最好的方式。 他显示转换datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
区,如datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
但他没有说明如何获得用户的时区...
这个人https://stackoverflow.com/a/7465359/523051说“ localize
调整为夏令时, replace
没有”
我看到使用pytz的每个人都提供他们自己的时区( users_timezone = timezone("US/Pacific")
),我不明白,因为你不知道这是你的观众在哪里...
这个家伙https://stackoverflow.com/a/4771733/523051有一种自动检测时区的方法,但这是使用dateutil
库,而不是像Armin Ronacher和官方python docs推荐的pytz( http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior ,就在黄色框中的锚点上方)
我需要的是最简单,面向未来的2012-08-25 10:59:56.511479
节省时间/等等,以考虑我的datetime.utcnow()标记( 2012-08-25 10:59:56.511479
),将其转换为用户的时区。 并显示如下:
Aug 25 - 10:59AM
如果今年不是当年,我想说
Aug 25 '11 - 10:59AM
好吧,在这里(也是,我对SO的第一次贡献:))
它确实需要2个外部库,可能会丢掉一些...
from datetime import datetime
from dateutil import tz
import pytz
def standard_date(dt):
"""Takes a naive datetime stamp, tests if time ago is > than 1 year,
determines user's local timezone, outputs stamp formatted and at local time."""
# determine difference between now and stamp
now = datetime.utcnow()
diff = now - dt
# show year in formatting if date is not this year
if (diff.days / 365) >= 1:
fmt = "%b %d '%y @ %I:%M%p"
else:
fmt = '%b %d @ %I:%M%p'
# get users local timezone from the dateutils library
# http://stackoverflow.com/a/4771733/523051
users_tz = tz.tzlocal()
# give the naive stamp timezone info
utc_dt = dt.replace(tzinfo=pytz.utc)
# convert from utc to local time
loc_dt = utc_dt.astimezone(users_tz)
# apply formatting
f = loc_dt.strftime(fmt)
return f
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.