如何使用python获取UTC日期时间,自动检测用户时区,并将日期时间转换为所需格式?

chr*_*kso 6 python timezone datetime utc

关于UTC日期时间转换有很多问题,似乎没有"最佳方式"的共识.

根据这个:http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/,pytz是最好的方式.他表示转换到这样的时区,datetime.datetime.utcnow().replace(tzinfo=pytz.utc)但他没有说如何获得用户的时区......

这家伙/sf/answers/522575161/说" localize调整夏令时,replace不"

我看到使用pytz的每个人都提供他们自己的时区(users_timezone = timezone("US/Pacific")),我不明白,因为你不知道这是你的观众在哪里...

这个家伙/sf/answers/334021341/有一种自动检测时区的方法,但这是使用dateutil库,而不是像Armin Ronacher和官方python docs(http)所推荐的pytz ://docs.python.org/library/datetime.html#strftime-and-strptime-behavior,就在黄色框中的锚点上方)

我需要的是最简单,面向未来的全天候节省时间/等等,考虑采用我的datetime.utcnow()标记(2012-08-25 10:59:56.511479),将其转换为用户的时区.并显示如下:

Aug 25 - 10:59AM
Run Code Online (Sandbox Code Playgroud)

如果今年不是当年,我想说

Aug 25 '11 - 10:59AM
Run Code Online (Sandbox Code Playgroud)

chr*_*kso 4

好吧,这就是(也是我对 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
Run Code Online (Sandbox Code Playgroud)