如何仅使用标准库将 UTC 日期时间转换为本地日期时间? [英] How to convert a UTC datetime to a local datetime using only standard library?

查看:86
本文介绍了如何仅使用标准库将 UTC 日期时间转换为本地日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 datetime.utcnow() 创建并保存在数据库中的 python datetime 实例.

为了显示,我想将从数据库中检索到的 datetime 实例转换为使用默认本地时区的本地 datetime(即,就好像 datetime 是使用 datetime.now() 创建的.

如何仅使用 python 标准库(例如,没有 pytz 依赖项)将 UTC datetime 转换为本地 datetime?

似乎一种解决方案是使用 datetime.astimezone(tz),但是如何获得默认的本地时区?

解决方案

我想我想通了:计算自纪元以来的秒数,然后使用 time.localtime 转换为本地 timzeone,然后将时间结构转换回日期时间...

EPOCH_DATETIME = datetime.datetime(1970,1,1)SECONDS_PER_DAY = 24*60*60def utc_to_local_datetime(utc_datetime):delta = utc_datetime - EPOCH_DATETIMEutc_epoch = SECONDS_PER_DAY * delta.days + delta.secondstime_struct = time.localtime(utc_epoch)dt_args = time_struct[:6] + (delta.microseconds,)返回日期时间.日期时间( *dt_args )

它正确地应用了夏季/冬季 DST:

<预><代码>>>>utc_to_local_datetime( datetime.datetime(2010, 6, 6, 17, 29, 7, 730000) )datetime.datetime(2010, 6, 6, 19, 29, 7, 730000)>>>utc_to_local_datetime( datetime.datetime(2010, 12, 6, 17, 29, 7, 730000) )datetime.datetime(2010, 12, 6, 18, 29, 7, 730000)

I have a python datetime instance that was created using datetime.utcnow() and persisted in database.

For display, I would like to convert the datetime instance retrieved from the database to local datetime using the default local timezone (i.e., as if the datetime was created using datetime.now()).

How can I convert the UTC datetime to a local datetime using only python standard library (e.g., no pytz dependency)?

It seems one solution would be to use datetime.astimezone(tz), but how would you get the default local timezone?

解决方案

I think I figured it out: computes number of seconds since epoch, then converts to a local timzeone using time.localtime, and then converts the time struct back into a datetime...

EPOCH_DATETIME = datetime.datetime(1970,1,1)
SECONDS_PER_DAY = 24*60*60

def utc_to_local_datetime( utc_datetime ):
    delta = utc_datetime - EPOCH_DATETIME
    utc_epoch = SECONDS_PER_DAY * delta.days + delta.seconds
    time_struct = time.localtime( utc_epoch )
    dt_args = time_struct[:6] + (delta.microseconds,)
    return datetime.datetime( *dt_args )

It applies the summer/winter DST correctly:

>>> utc_to_local_datetime( datetime.datetime(2010, 6, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 6, 6, 19, 29, 7, 730000)
>>> utc_to_local_datetime( datetime.datetime(2010, 12, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 12, 6, 18, 29, 7, 730000)

这篇关于如何仅使用标准库将 UTC 日期时间转换为本地日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆