Python-将UTC毫秒时间戳转换为本地时间

时间:2018-09-21 21:10:26

标签: python datetime timezone

我有一个Unix时间戳(以毫秒为单位),并且需要获取本地时间的日期字符串。

这是我的代码:

date = datetime.utcfromtimestamp(timestamp / 1000).strftime('%d-%m-%Y')
hour = datetime.utcfromtimestamp(timestamp / 1000).strftime('%H')
month = datetime.utcfromtimestamp(timestamp / 1000).strftime('%m')
monthName = calendar.month_name[int(month)]
weekDay = calendar.day_name[(datetime.strptime(date, '%d-%m-%Y')).weekday()]

通过上述函数生成的原始时间戳以及所得的日期,小时和所有其他值均以UTC表示。如何更改我的代码以在本地时间获取它?

1 个答案:

答案 0 :(得分:3)

要将UTC毫秒时间戳转换为可识别时区的datetime,您可以执行以下操作:

代码:

def tz_from_utc_ms_ts(utc_ms_ts, tz_info):
    """Given millisecond utc timestamp and a timezone return dateime

    :param utc_ms_ts: Unix UTC timestamp in milliseconds
    :param tz_info: timezone info
    :return: timezone aware datetime
    """
    # convert from time stamp to datetime
    utc_datetime = dt.datetime.utcfromtimestamp(utc_ms_ts / 1000.)

    # set the timezone to UTC, and then convert to desired timezone
    return utc_datetime.replace(tzinfo=pytz.timezone('UTC')).astimezone(tz_info)

测试代码:

import datetime as dt
import pytz

utc_ts = 1537654589000
utc_time = "Sat Sep 22 22:16:29 2018 UTC"
pdt_time = "Sat Sep 22 15:16:29 2018 PDT"

tz_dt = tz_from_utc_ms_ts(utc_ts, pytz.timezone('America/Los_Angeles'))

print(tz_dt)
print(tz_dt.strftime('%d-%m-%Y'))

结果:

2018-09-22 15:16:29-07:00
22-09-2018