Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert local time string to UTC?

How do I convert a datetime string in local time to a string in UTC time?

I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.

Clarification: For example, if I have 2008-09-17 14:02:00 in my local timezone (+10), I'd like to generate a string with the equivalent UTC time: 2008-09-17 04:02:00.

Also, from http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.

like image 241
Tom Avatar asked Sep 17 '08 03:09

Tom


People also ask

How do you convert local time to UTC?

Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.). Note The date also follows UTC format.

How do you convert string to UTC time in Python?

Python convert a string to datetime with timezone In this example, I have imported a module called timezone. datetime. now(timezone('UTC')) is used to get the present time with timezone. The format is assigned as time = “%Y-%m-%d %H:%M:%S%Z%z”.

How do you convert local time to UTC in node JS?

Use the toUTCString() method to convert local time to UTC, e.g. new Date(). toUTCString() . The toUTCString() method converts a date to a string, using the UTC time zone. Copied!

What is UTC time string?

Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z"). Times are expressed in local time, together with a time zone offset in hours and minutes. A time zone offset of "+hh:mm" indicates that the date/time uses a local time zone which is "hh" hours and "mm" minutes ahead of UTC.


1 Answers

First, parse the string into a naive datetime object. This is an instance of datetime.datetime with no attached timezone information. See its documentation.

Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.

Finally, use datetime.astimezone() method to convert the datetime to UTC.

Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":

from datetime import datetime    import pytz  local = pytz.timezone("America/Los_Angeles") naive = datetime.strptime("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S") local_dt = local.localize(naive, is_dst=None) utc_dt = local_dt.astimezone(pytz.utc) 

From there, you can use the strftime() method to format the UTC datetime as needed:

utc_dt.strftime("%Y-%m-%d %H:%M:%S") 
like image 75
John Millikin Avatar answered Sep 24 '22 08:09

John Millikin