有很多关于UTC日期时间转换的问题,似乎没有一个“最佳方式”的共识。
根据这个:http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/,pytz是最好的方法。他展示了如何转换成时区,但他没有说明如何获取用户的时区…
这家伙说“根据夏令时调整,datetime.datetime.utcnow().replace(tzinfo=pytz.utc)不”
我看到的每一个使用pytz的人都在提供他们自己的时区(localize),我不明白,因为你不知道你的观众在哪里……
这家伙有一种自动检测时区的方法,但这是使用replace库,而不是pytz,正如armin ronacher和python官方文档所建议的那样(https://stackoverflow.com/a/7465359/523051,就在黄色框中的锚上方)
我所需要的是最简单的、经得起未来考验的、所有夏时制的时间/etc,以这种方式获取我的datetime.utcnow()标记(users_timezone = timezone("US/Pacific")),并将其转换为用户的时区。像这样展示:

Aug 25 - 10:59AM

如果今年不是现在,我想说
Aug 25 '11 - 10:59AM

最佳答案

好的,这是(同时,我对so的第一个贡献:)
它确实需要两个外部库,这可能会导致一些…

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

07-25 20:20
查看更多