简体   繁体   English

将Python中的unix时间戳转换为日期时间,并使2小时后退

[英]Convert unix timestamp in Python to datetime and make 2 Hours behind

I have this code, recieve a unix timestamp from a server which is 2 hours ahead of my time. 我有这个代码,从服务器收到一个unix时间戳,比我的时间早2个小时。 My time is SAST and theirs is GMT +2. 我的时间是SAST,他们的时间是GMT +2。

I convert this timestamp in python to a readable datetime like this 我将python中的这个时间戳转换为这样的可读日期时间

import datetime

unixtimestamp = 1507126064
datetime.datetime.fromtimestamp(unixtimestamp).strftime('%Y-%m-%d %H:%M:%S')

The problem is that this time comes back two hours ahead of me, so what would be the easiest way to minus two hours or make it local time. 问题是这个时间比我早两个小时回来,所以最简单的方法是减去两个小时或者当地时间。

With datetime.timedelta object: 使用datetime.timedelta对象:

from datetime import datetime, timedelta

unix_ts = 1507126064
dt = (datetime.fromtimestamp(unix_ts) - timedelta(hours=2)).strftime('%Y-%m-%d %H:%M:%S')
print(dt)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM