Python datetime and utc offset conversion ignoring

2019-07-20 13:29发布

问题:

I have two operations I want to perform, one the inverse of the other.

  1. I have a UNIX timestamp at UTC, say for instance, 1425508527. From this I want to get the year, month, day etc. given a UTC offset. EG. what is the year/month/day/time in (UTC -6 hours)? The answer is March 4, 2015 at 16:35:27. Without providing an offset (or offset zero) the answer should be March 4, 2015 at 22:35:27.

  2. Now I have the date at some location, along with the UTC offset. For instance March 4, 2015 at 16:35:27 and the offset (UTC -6 hours). The UNIX UTC timestamp I should get should be 1425508527.

I am able to almost do 2. (using python datetime library) like this:

import datetime.datetime as datetime
import time
import dateutil.tz as tz

utc_offset = 6
time.mktime(datetime(2015,3,4,16,35,27,
                     tzinfo=tz.tzoffset(None, utc_offset*60*60)).utctimetuple())
# => 1425486927

The problem with the above is that utc_offset has to be given the wrong sign. According to this map, utc_offset should be set to -6. Number 1. I've had no luck with. I don't need/want to deal with timezone information like daylight savings time. How do I implement this in Python?

回答1:

If your system uses Unix time, which does not count leap seconds, then the conversion can be done as follows:

Part 1: timestamp and offset to local date

import datetime as DT
import calendar

timestamp = 1425508527
offset = -6

date = DT.datetime(1970,1,1) + DT.timedelta(seconds=timestamp)
print(date)
# 2015-03-04 22:35:27

localdate = date + DT.timedelta(hours=offset)
print(localdate)
# 2015-03-04 16:35:27

Part 2: local date and offset to timestamp

utcdate = localdate - DT.timedelta(hours=offset)
assert date == utcdate

timetuple = utcdate.utctimetuple()
timestamp2 = calendar.timegm(timetuple)
print(timestamp2)
# 1425508527
assert timestamp == timestamp2