1

A Python script running on a server in NYC receives a stream of live data from a websocket API where only the time is given, eg: 8:21:56. The provided time is in the timezone Asia/Chongqing which is UTC +08:00. The local server is in the timezone America/New_York which is UTC -05:00.

This means that the dates in both timezones are different for 12-13 hours every day depending on daylight savings.

Question: Knowing that my server is in a different timezone, how can I find the date needed to convert the time into an appropriate datetime? Eg: If the local date on the server is 2015-12-05, convert 8:21:56 to 2015-12-06 7:36:56.000Z in the UTC timezone.

Nyxynyx
  • 61,411
  • 155
  • 482
  • 830
  • Possible duplicate of [How do I convert local time to UTC in Python?](http://stackoverflow.com/questions/79797/how-do-i-convert-local-time-to-utc-in-python) – Remi Guan Dec 06 '15 at 00:40
  • @KevinGuan In the SO question linked, the date is given. For this question, the date from the websocket stream can be different from the date in the local server, so it is not so straight forward – Nyxynyx Dec 06 '15 at 00:44
  • I think that doesn't matter because that question's accepted answer let you *set the timezone manually*. So you can set the timezone which you need covert from. – Remi Guan Dec 06 '15 at 00:48

1 Answers1

0

America/New_York like many other timezones may have different utc offsets at different dates.

To get the date in one time zone (Asia/Chongqing) corresponding to a given time ('8:21:56') in that time zone (Asia/Chongqing) assuming you know the date in another time zone (America/New_York), you should create an algorithm similar to pytz's .localize() method where the difficult part is to convert local time to UTC that is not always possible -- the rest is straightforward (if you know UTC date/time and the zone id such as Asia/Chongqing then it is easy (utc_dt.astimezone(tz).date()) to get date in Asia/Chongqing.

You could simplify the algorithm if you need to support only a fixed number of timezones in a given date range.

jfs
  • 399,953
  • 195
  • 994
  • 1,670