使用python标准库将python UTC datetime转换为本地datetime? [英] Convert a python UTC datetime to a local datetime using only python standard library?

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

问题描述

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

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

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

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()).

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

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

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

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

推荐答案

我想我想出来:计算自从历元以来的秒数,然后转换为本地timzeone使用time.localtime,然后将时间结构转换回datetime ...

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 )

正确地应用夏/冬DST: p>

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)

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

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