I'm receiving a date in a fixed timezone. I need to convert it to the local machine's timezone, but I don't know what that is. How can I do this using pytz (not dateutil)? I've found plenty of solutions which use dateutil, e.g. this answer, but I can't find a similar function in pytz.
Asked
Active
Viewed 1,251 times
1 Answers
1
You can convert via a (UTC) Unix timestamp:
foreign_naive = datetime.datetime(2012, 3, 11, 6, 0, 0)
foreign_timezone = 'US/Eastern'
foreign_dt = pytz.timezone(foreign_timezone).localize(foreign_naive)
timestamp = time.mktime(foreign_dt).astimezone(pytz.utc).timetuple()
local_dt = datetime.datetime.fromtimestamp(timestamp)
This uses the solution from Python Create unix timestamp five minutes in the future.
Note that this won't tell you what the local timezone is, although you can find out its offset from UTC at that time using:
(local_dt - datetime.datetime.utcfromtimestamp(timestamp)).seconds
-
Knowing the current offset from UTC won't be useful in any timezone using daylight saving time. – Mark Ransom Sep 04 '12 at 14:40
-
@MarkRansom that's not a problem; comparing `datetime.datetime.fromtimestamp` to `datetime.datetime.utcfromtimestamp` gives you the offset at `timestamp`. – ecatmur Sep 04 '12 at 14:54
-
The original question states the local machine's timezone is unknown. – Mark Ransom Sep 04 '12 at 15:23
-
@MarkRansom right, and you don't need to know the local machine's timezone to use `datetime.datetime.fromtimestamp`. – ecatmur Sep 04 '12 at 15:30