将带有时区的UTC日期时间转换为本地 [英] Convert UTC datetime with timezone to local

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

问题描述

我有一个带UTC和tzinfo日期的字符串

  2015年10月1日,星期四00:02:01 + 0200 

如何将其转换为本地时间,以便输出

  2015-10-02 02:02:01 

我试过

  parser.parse( Thu,01 Oct 2015 00:02: 01 +0200)

但我找不到一种方法可以将tzinfo汇总为

预先感谢



编辑:问题不同,因为其中包括时间差给定的字符串,重点是添加或减少有时需要更改日期的时差,如在提供的示例中一样。

解决方案

这是一个stdlib解决方案:

 #!/ usr / bin / env python 
从datetime导入datetime
从email.utils导入parsedate_tz,mktime_tz

timestamp = mktime_tz(parsedate_tz( Thu,01 2015年10月00:02:01 +0200))
print(datetime.fromtimestamp(timestamp))#获取本地时间

输入的时间格式为 rfc 5322时间格式 电子邮件模块理解。如果 datetime.fromtimestamp()如果未在给定平台上使用历史时区数据库,则对于过去/将来的日期可能会失败。一种可移植的解决方案是使用 pytz 模块,以访问tz数据库:

 #!/ usr / bin / env python 
从datetime导入datetime
从email.utils导入parsedate_tz,mktime_tz
导入tzlocal#$ pip安装tzlocal

local_timezone = tzlocal.get_localzone()#返回pytz tzinfo
timestamp = mktime_tz(parsedate_tz( Thu,01 Oct 2015 00:02:01 +0200))
print(datetime.fromtimestamp(timestamp) ,local_timezone))


I have a string with a date in UTC and tzinfo

"Thu, 01 Oct 2015 00:02:01 +0200"

How can I do to convert it to my local time so it outputs

"2015-10-02 02:02:01"

I tried

parser.parse("Thu, 01 Oct 2015 00:02:01 +0200")

but I can't find a way to sum this tzinfo to the time to get my local time.

Thanks in advance

Edit: The question is diferent as It includes time diference in the given string and the point is to add or sutract this time diference that sometimes requires to change the date as in the provided example.

解决方案

Here's a stdlib solution:

#!/usr/bin/env python
from datetime import datetime
from email.utils import parsedate_tz, mktime_tz

timestamp = mktime_tz(parsedate_tz("Thu, 01 Oct 2015 00:02:01 +0200"))
print(datetime.fromtimestamp(timestamp)) # get local time

The input time format is rfc 5322 time format that is understood by email module. datetime.fromtimestamp() may fail for past/future dates if it doesn't use a historical time zone database on a given platform. A portable solution is to use pytz module, to get access to the tz database:

#!/usr/bin/env python
from datetime import datetime
from email.utils import parsedate_tz, mktime_tz
import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone() # return pytz tzinfo
timestamp = mktime_tz(parsedate_tz("Thu, 01 Oct 2015 00:02:01 +0200"))
print(datetime.fromtimestamp(timestamp, local_timezone))

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

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