Python-将UTC毫秒时间戳转换为本地时间 [英] Python - converting UTC millisecond timestamp to local time
本文介绍了Python-将UTC毫秒时间戳转换为本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Unix时间戳(以毫秒为单位),需要获取本地时间的日期字符串。
I have a Unix epoch timestamp in milliseconds and need to get date string in local time.
这是我的代码:
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表示。如何更改我的代码以在本地时间获取它?
The original timestamp and the resulting date, hour and all other values generated from the above functions are in UTC. How can I change my code to get it in local time?
推荐答案
要将UTC毫秒时间戳转换为可识别时区的 datetime
,您可以执行以下操作:
To convert a UTC millisecond timestamp into a timezone aware datetime
, you can do:
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)
测试代码:
Test Code:
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'))
结果:
Results:
2018-09-22 15:16:29-07:00
22-09-2018
这篇关于Python-将UTC毫秒时间戳转换为本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文