我从来没有在UTC和UTC之间转换过时间。最近有一个请求,让我的应用程序具有时区感知,我一直在兜圈子。大量关于将本地时间转换为UTC的信息,我发现这些信息相当简单(可能我也做错了),但我找不到任何关于将UTC时间轻松转换为最终用户时区的信息。

简而言之,和android应用程序发送给我(appengine应用程序)数据,在该数据是一个时间戳。存储时间戳到utc时间我正在使用:

datetime.utcfromtimestamp(timestamp)

这似乎起作用了。当我的应用程序存储数据时,它被存储为5小时前(我是EST -5)

数据被存储在appengine的BigTable上,当检索到它时,它是一个像这样的字符串:

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

如何将此字符串转换为用户正确时区的日期时间?

另外,用户时区信息的推荐存储是什么?(你通常如何存储tz信息,如:“-5:00”或“EST”等?)我确信我第一个问题的答案可能包含第二个问题的答案的参数。


当前回答

你可以使用箭头

from datetime import datetime
import arrow

now = datetime.utcnow()

print(arrow.get(now).to('local').format())
# '2018-04-04 15:59:24+02:00'

你可以用任何东西来喂arrow.get()。时间戳,iso字符串等

其他回答

你可以使用日历。timegm将您的时间转换为Unix纪元和时间以来的秒数。转换回本地时间:

import calendar
import time

time_tuple = time.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S")
t = calendar.timegm(time_tuple)

print time.ctime(t)

给出星期五2011年1月21日05:37:21(因为我在UTC+03:00时区)。

将franksand的答案整合成一种方便的方法。

import calendar
import datetime

def to_local_datetime(utc_dt):
    """
    convert from utc datetime to a locally aware datetime according to the host timezone

    :param utc_dt: utc datetime
    :return: local timezone datetime
    """
    return datetime.datetime.fromtimestamp(calendar.timegm(utc_dt.timetuple()))

你可以使用箭头

from datetime import datetime
import arrow

now = datetime.utcnow()

print(arrow.get(now).to('local').format())
# '2018-04-04 15:59:24+02:00'

你可以用任何东西来喂arrow.get()。时间戳,iso字符串等

下面是一个快速而简单的版本,它使用本地系统设置来计算时差。注意:如果您需要转换到当前系统未运行的时区,这将不起作用。我已经在BST时区下测试了英国设置

from datetime import datetime
def ConvertP4DateTimeToLocal(timestampValue):
   assert isinstance(timestampValue, int)

   # get the UTC time from the timestamp integer value.
   d = datetime.utcfromtimestamp( timestampValue )

   # calculate time difference from utcnow and the local system time reported by OS
   offset = datetime.now() - datetime.utcnow()

   # Add offset to UTC time and return it
   return d + offset

我通常将此延迟到前端——从后端以UTC时间戳或其他日期时间格式发送时间,然后让客户端计算时区偏移量,并以适当的时区呈现此数据。

对于web应用程序,这在javascript中很容易做到——你可以使用内置方法很容易地计算出浏览器的时区偏移量,然后从后端正确地呈现数据。