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

标签 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。如何更改我的代码以在本地时间获取它?

最佳答案

要将 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

关于Python - 将 UTC 毫秒时间戳转换为本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52451105/

相关文章:

python - 没有名为 'mlxtend' 的模块

python - 将用户名存储在Google App Engine上,而不是每次都调用get_current_user?

Perl:解码二进制文件中的时间戳

mysql - 如何创建配置了 time_zone 的 mysql+pymysql 引擎?

php - 时区和夏令时问题

python - Python依赖 hell : A compromise between virtualenv and global dependencies?

Python OpenCV : inRange() stopped working without change

MySQL 选择过去的日期 : Problem with MAX and GROUP BY

php - DateTime 对象上的不同 timezone_types

angular - 将数据导出到 excel 时,日期会根据时区发生变化。如何避免?