Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, how do I create a timezone aware datetime from a date and time?

In Python, let's say I have a date of 25 December 2016. How can I create a timezone-aware datetime of noon on that date?

Bonus points if it's compatible with Django's timezone handling.

like image 245
seddonym Avatar asked Apr 14 '16 12:04

seddonym


People also ask

How do you make a datetime timezone aware?

Timezone aware object using datetime now(). time() function of datetime module. Then we will replace the value of the timezone in the tzinfo class of the object using the replace() function. After that convert the date value into ISO 8601 format using the isoformat() method.

How do you set the timezone in Python?

The parameter pytz. timezone allows us to specify the timezone information as a string. We can pass in any available timezone and will get the current date time of that timezone, and it will also print the offset with respect to the UTC. i.e., the difference between UTC timezone(+00:00) and the specified time zone.

How do you use UTC datetime in Python?

You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object.


2 Answers

The trick is to first combine the naive time and the date into a naive datetime. This naive datetime can then be converted to an aware datetime.

The conversion can be done using the third party package pytz (using, in this case, the 'Europe/London' timezone):

import datetime
import pytz

naive_time = datetime.time(0, 30)
date = datetime.date(2016, 12, 25)
naive_datetime = datetime.datetime.combine(date, naive_time)

timezone = pytz.timezone('Europe/London')
aware_datetime = timezone.localize(naive_datetime) 

If you're doing it in Django, and want to use the current timezone (as configured in Django), you can replace the final two lines with a call to make_aware:

from django.utils import timezone

aware_datetime = timezone.make_aware(naive_datetime)
like image 101
seddonym Avatar answered Sep 23 '22 18:09

seddonym


Erik's answer to this question explains why you should use datetime.combine() followed by timezone.localize(). Setting the timezone directly on the datetime.time instance will not take the date into account, which could leave you with an incorrect result (due to daylight savings or even historic transitions). datetime.combine() just isn't that smart!

>>> import pytz
>>> import datetime
>>> d = datetime.date(2016, 12, 25)
>>> t = datetime.time(12)
>>> tz = pytz.timezone('US/Pacific')
>>> tz.localize(datetime.datetime.combine(d,t))
datetime.datetime(2016, 12, 25, 12, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)
like image 32
Neal Gokli Avatar answered Sep 20 '22 18:09

Neal Gokli