Convert UTC datetime string to local datetime

python convert utc to local pytz
python timezone conversion
convert datetime to timezone
datetime datetime to timezone
datetime utc
python convert datetime zone
convert gmt to cst python
django convert datetime to timezone

I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily converting the UTC time to the end-users timezone.

In a nutshell, and android app sends me (appengine app) data and within that data is a timestamp. To store that timestamp to utc time I am using:

datetime.utcfromtimestamp(timestamp)

That seems to be working. When my app stores the data, it is being store as 5 hours ahead (I am EST -5)

The data is being stored on appengine's BigTable, and when retrieved it comes out as a string like so:

"2011-01-21 02:37:21"

How do I convert this string to a DateTime in the users correct time zone?

Also, what is the recommended storage for a users timezone information? (How do you typically store tz info ie: "-5:00" or "EST" etc etc ?) I'm sure the answer to my first question might contain a parameter the answers the second.

If you don't want to provide your own tzinfo objects, check out the python-dateutil library. It provides tzinfo implementations on top of a zoneinfo (Olson) database such that you can refer to time zone rules by a somewhat canonical name.

from datetime import datetime
from dateutil import tz

# METHOD 1: Hardcode zones:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')

# METHOD 2: Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')

# Tell the datetime object that it's in UTC time zone since 
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)

# Convert time zone
central = utc.astimezone(to_zone)

Edit Expanded example to show strptime usage

Edit 2 Fixed API usage to show better entry point method

Edit 3 Included auto-detect methods for timezones (Yarin)

Convert UTC date time to local date time, Append 'UTC' to the string before converting it to a date in javascript: var date = new Date('6/29/2011 4:52:48 PM UTC'); date.toString() // "Wed Jun 29 2011  The ToLocalTime method converts a DateTime value from UTC to local time. To convert the time in any designated time zone to local time, use the TimeZoneInfo.ConvertTime method. The value returned by the conversion is a DateTime whose Kind property always returns Local.

Here's a resilient method that doesn't depend on any external libraries:

from datetime import datetime
import time

def datetime_from_utc_to_local(utc_datetime):
    now_timestamp = time.time()
    offset = datetime.fromtimestamp(now_timestamp) - datetime.utcfromtimestamp(now_timestamp)
    return utc_datetime + offset

This avoids the timing issues in DelboyJay's example. And the lesser timing issues in Erik van Oosten's amendment.

As an interesting footnote, the timezone offset computed above can differ from the following seemingly equivalent expression, probably due to daylight savings rule changes:

offset = datetime.fromtimestamp(0) - datetime.utcfromtimestamp(0) # NO!

Update: This snippet has the weakness of using the UTC offset of the present time, which may differ from the UTC offset of the input datetime. See comments on this answer for another solution.

To get around the different times, grab the epoch time from the time passed in. Here's what I do:

def utc2local (utc):
    epoch = time.mktime(utc.timetuple())
    offset = datetime.fromtimestamp (epoch) - datetime.utcfromtimestamp (epoch)
    return utc + offset

How to translate UTC to your time | Astronomy Essentials, How do I convert UTC datetime to local datetime in Python? Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Convert UTC datetime string to local datetime. 497

See the datetime documentation on tzinfo objects. You have to implement the timezones you want to support yourself. The are examples at the bottom of the documentation.

Here's a simple example:

from datetime import datetime,tzinfo,timedelta

class Zone(tzinfo):
    def __init__(self,offset,isdst,name):
        self.offset = offset
        self.isdst = isdst
        self.name = name
    def utcoffset(self, dt):
        return timedelta(hours=self.offset) + self.dst(dt)
    def dst(self, dt):
            return timedelta(hours=1) if self.isdst else timedelta(0)
    def tzname(self,dt):
         return self.name

GMT = Zone(0,False,'GMT')
EST = Zone(-5,False,'EST')

print datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(GMT).strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(EST).strftime('%m/%d/%Y %H:%M:%S %Z')

t = datetime.strptime('2011-01-21 02:37:21','%Y-%m-%d %H:%M:%S')
t = t.replace(tzinfo=GMT)
print t
print t.astimezone(EST)
Output
01/22/2011 21:52:09 
01/22/2011 21:52:09 GMT
01/22/2011 16:52:09 EST
2011-01-21 02:37:21+00:00
2011-01-20 21:37:21-05:00a

Python, can be performed by calling the astimezone() technique with tz. tzutc() . This ISO string format is input into DateTimeUtil::parse and System.DateTime::Parse. to convert the string to a date/time type. Sample of Converting Between Date/Time and String. The following X++ code sample shows how compatible strings can be passed between .NET and X++ and converted into date/time variables.

If you want to get the correct result even for the time that corresponds to an ambiguous local time (e.g., during a DST transition) and/or the local utc offset is different at different times in your local time zone then use pytz timezones:

#!/usr/bin/env python
from datetime import datetime
import pytz    # $ pip install pytz
import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone() # get pytz tzinfo
utc_time = datetime.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S")
local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(local_timezone)

DateTime.ToLocalTime Method (System), How do I convert UTC to local time in Excel? Then, if you want to convert it back into a string, you can do something like: var s = dateTimeAsUtc.ToString("O"); Which will give you a nice representation: 2017-01-02T10:00:00.0000000Z You are lucky you are interested in UTC. The datetime class can only do UTC, "local" (whatever that is), or "Unspecified".

This answer should be helpful if you don't want to use any other modules besides datetime.

datetime.utcfromtimestamp(timestamp) returns a naive datetime object (not an aware one). Aware ones are timezone aware, and naive are not. You want an aware one if you want to convert between timezones (e.g. between UTC and local time).

If you aren't the one instantiating the date to start with, but you can still create a naive datetime object in UTC time, you might want to try this Python 3.x code to convert it:

import datetime

d=datetime.datetime.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S") #Get your naive datetime object
d=d.replace(tzinfo=datetime.timezone.utc) #Convert it to an aware datetime object in UTC time.
d=d.astimezone() #Convert it to your local timezone (still aware)
print(d.strftime("%d %b %Y (%I:%M:%S:%f %p) %Z")) #Print it with a directive of choice

Be careful not to mistakenly assume that if your timezone is currently MDT that daylight savings doesn't work with the above code since it prints MST. You'll note that if you change the month to August, it'll print MDT.

Another easy way to get an aware datetime object (also in Python 3.x) is to create it with a timezone specified to start with. Here's an example, using UTC:

import datetime, sys

aware_utc_dt_obj=datetime.datetime.now(datetime.timezone.utc) #create an aware datetime object
dt_obj_local=aware_utc_dt_obj.astimezone() #convert it to local time

#The following section is just code for a directive I made that I liked.
if sys.platform=="win32":
    directive="%#d %b %Y (%#I:%M:%S:%f %p) %Z"
else:
    directive="%-d %b %Y (%-I:%M:%S:%f %p) %Z"

print(dt_obj_local.strftime(directive))

If you use Python 2.x, you'll probably have to subclass datetime.tzinfo and use that to help you create an aware datetime object, since datetime.timezone doesn't exist in Python 2.x.

How to convert between UTC and local time in Python, Converts the value of the current DateTime object to local time. to local time, and the DateTime // structure converted to universal time. public static string 5/6​/2005 02:34:42 PM, Kind = Utc ToLocalTime: 5/6/2005 07:34:42 AM, Kind = Local​  Java 8 – Parse string to date-time in UTC By Lokesh Gupta | Filed Under: Java Date/Time Learn to parse a given date time string to instance e.g. ZonedDateTime or OffsetDateTime classes, using DateTimeFormatter class in Java 8.

Format ZonedDateTime to String, fromtimestamp() to convert from UTC to local time. Call datetime. datetime. strftime(fmt) with fmt as "%s" to convert the UTC datetime. how to convert UTC DateTime to local datetime in C#? I want method which returns the string datetime in target locale format by taking the UTC DateTime and UTC DateTime offset in c#, here is the example code

How to Convert a String to Date in Java, Learn how to convert ZonedDateTime to String and vice-versa in Java. ZonedDateTime.of(localDateTime, ZoneId.of( "UTC" ));  To convert UTC to local time, call the ToLocalTime method of the DateTime object whose time you want to convert. The exact behavior of the method depends on the value of the object’s Kind property, as the following table shows.

How to Convert String to LocalDateTime in Java 8, The Date/Time API in Java works with the ISO 8601 format by default, which is store time as a millisecond offset since epoch, but rather simply the current date. To convert a string to a LocalTime object, it's enough to write: The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.

Comments
  • related: How to convert a python utc datetime to a local datetime using only python standard library?
  • This answer shows how to solve this in a simple way.
  • On my previous comment, I was able to import dateutil.tz and use tz.tzutc() and tz.tzlocal() as time zone objects I was looking for. It looks like the time zone database on my system is good (I checked in /usr/share/zoneinfo). Not sure what was up.
  • @Benjamin You are on the right track. The tz module is the correct entry point to be using for this library. I've updated my answer to reflect this. The dateutil.zoneinfo module I was showing previously is used internally by the tz module as a fall back if it can't locate the system's zoneinfo DB. If you look inside the library you'll see that there's a zoneinfo DB tarball in the package that it uses if it can't find your system's DB. My old example was trying to hit that DB directly and I'm guessing you were having issues loading that private DB (isn't on the python path somehow?)
  • @MattoTodd: utc -> local conversion is broken in dateutil, use pytz instead.
  • @J.F.Sebastian this is fixed in #225
  • @briankip It depends on how sophisticated your application needs to be, but in general applications, yes, it's a problem. First of all depending on what time of year it is, the number of hours to add/subtract might change as some time zones honor DST and other don't. Secondly, time zone rules are arbitrarily changed over time so if you're working with a past date/time you need to apply the rules that were valid at that point in time, not present time. That's why it's best to use an API that leverages the Olson TZ database behind the scenes.
  • This works well and requires nothing other than time and datetime.
  • @Mike_K: but it is incorrect. It doesn't support DST or timezones that had different utc offset in the past for other reasons. Full support without pytz-like db is impossible, see PEP-431. Though you can write stdlib-only solution that works in such cases on systems that already have historical timezone db e.g., Linux, OS X, see my answer.
  • @J.F.Sebastian: You say this code doesn't work in general but also say it works on OS X and Linux. Do you mean this code doesn't work on Windows?
  • @DavidFoster: your code may fail on Linux and OS X too. The difference between yours and mine stdlib-only solutions is that yours uses current offset that might be different from utc offset at utc_datetime time.
  • Good call. That's a very subtle difference. The UTC offset can change over time too. sigh