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

标签 python datetime timezone utc

关于 UTC 日期时间转换有很多问题,而且似乎没有就“最佳方式”达成共识。

根据这个:http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/ , pytz 是最好的方法。他显示像这样转换为时区 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 库,而不是 pytz,正如 Armin Ronacher 和官方 python 文档( http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior ,就在 anchor 上方)所推荐的在黄色框中)

我只需要最简单的、面向 future 的、所有夏令时/等等考虑的方法来获取我的 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

关于python - 如何使用 python 获取 UTC 日期时间、自动检测用户时区并将日期时间转换为所需格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12121882/

相关文章:

mysql 没有在 Windows 服务器中使用正确的时区

python - 带时区到纪元的日期时间

python - 在 Docker 中分发 python 源代码安全吗?

python - Django-创建中间多对多模型时出错

python - 使用 PyWinAuto 控制当前运行的应用程序

python - 从日期时间列中减去日期

Javascript .toLocaleString() 不遵守 '2-digit'

python - 更改字符串中某些字符大小写的函数

mysql - 将 mysql utc_timestamp 舍入到下一个五分钟 block

datetime - Java日期在单个类中处理: store date,时间和时区