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

3
我是一位有用的助手,可以为您进行翻译。以下是需要翻译的内容:

我有一个以毫秒为单位的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时间。我该如何修改代码以获取本地时间?


@Acccumulation,您所标记的问题中,时间戳为datetime对象,而在我的问题中,时间戳是字符串对象。 - Tony Mathew
@TonyMathew - 当然可以,但是你的字符串来自于日期时间对象。因此,如果你能正确地操作日期时间对象,那么你就可以得到正确的字符串。 - John Y
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接