将UTC日期时间字符串转换为本地日期时间 [英] Convert UTC datetime string to local datetime

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

问题描述

我从来不需要将时间与UTC进行时间转换。最近有人要求我的应用注意时区,并且我一直在圈子里奔波。我发现很多有关将本地时间转换为UTC的信息,这很基本(也许我也做错了),但是我找不到任何有关将UTC时间轻松转换为最终用户时区的信息。

I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily converting the UTC time to the end-users timezone.

简而言之,Android应用程序向我发送了(appengine应用程序)数据,该数据中有一个时间戳。要将时间戳存储为utc时间,我正在使用:

In a nutshell, and android app sends me (appengine app) data and within that data is a timestamp. To store that timestamp to utc time I am using:

datetime.utcfromtimestamp(timestamp)

这似乎有效。当我的应用存储数据时,数据将提前5个小时存储(我是EST -5)

That seems to be working. When my app stores the data, it is being store as 5 hours ahead (I am EST -5)

数据正在存储在appengine的BigTable上,并在检索时存储像这样的字符串出来:

The data is being stored on appengine's BigTable, and when retrieved it comes out as a string like so:

"2011-01-21 02:37:21"

如何在用户正确的时区将此字符串转换为DateTime?

How do I convert this string to a DateTime in the users correct time zone?

此外,对于用户时区信息,建议的存储空间是什么? (您通常如何存储tz信息,即:-5:00或 EST等?)我确定第一个问题的答案可能包含一个参数,第二个问题的答案。

Also, what is the recommended storage for a users timezone information? (How do you typically store tz info ie: "-5:00" or "EST" etc etc ?) I'm sure the answer to my first question might contain a parameter the answers the second.

推荐答案

如果您不想提供自己的 tzinfo 对象,请查看 python-dateutil 库。它在 zoneinfo(Olson)数据库之上提供了 tzinfo 实现。

If you don't want to provide your own tzinfo objects, check out the python-dateutil library. It provides tzinfo implementations on top of a zoneinfo (Olson) database such that you can refer to time zone rules by a somewhat canonical name.

from datetime import datetime
from dateutil import tz

# METHOD 1: Hardcode zones:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')

# METHOD 2: Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')

# Tell the datetime object that it's in UTC time zone since 
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)

# Convert time zone
central = utc.astimezone(to_zone)

编辑展开示例以显示 strptime 的使用情况

Edit Expanded example to show strptime usage

编辑2 固定的API使用情况,以显示更好的入口点方法

Edit 2 Fixed API usage to show better entry point method

编辑3 包括的时区自动检测方法(雅林)

Edit 3 Included auto-detect methods for timezones (Yarin)

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

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