Convert Naive Datetime to Timezone aware in Python
In this tutorial, we are going to learn how to convert naive date-time to timezone aware in Python.
Let’s go over a few ways we can make date-time objects time zone aware.
What is datetime object?
Datetime is the name of one of the module within python and one of the other classes within the module.
It is an instance that represents a single point in time.
In order to get immediate datetime details, we use now method. It returns the details of time of the moment when now was called.
import datetime datetime.datetime.now()
Output:
datetime.datetime(2019, 10, 30, 19, 9, 31, 900482)
Formatting datetime objects
Here we will learn about extracting attributes and writing different formats of date.
The occasions where we want to display datetime object in a certain way, we use strftime method.
Let us, understand it with examples,
d = datetime.datetime(2019, 10, 30, 20, 15) d.strftime("%Y/%m/%d") > '2019/10/30' d.strftime("%d %b %y") > '30 Oct 19' d.strftime("%Y-%m-%d %H:%M:%S") > '2019-10-30 20:15:00'
Naive v/s Aware in Python
So far, we have only seen formatting datetime objects. That means the object is naive to any sort of time zones.
Timezone’s offset: how many hours the timezone is from Coordinated Universal Time (UTC).
Hence, a datetime object can either be naive offset or aware offset.
Generally, a naive timezone object does not contain any information about timezone. In order to check that we use, tzinfo.
import datetime naive = datetime.datetime.now() print(naive.tzinfo)
Output:
> None
To make a datetime object offset aware, we can use pytz library.
import datetime import pytz d = datetime.datetime.now() timezone = pytz.timezone("US/Pacific") d_aware = timezone.localize(d) d_aware.tzinfo
Output:
<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>
Converting Time-Zones
We import timezone package from pytz library.
from datetime import datetime from pytz import timezone date = "%Y-%m-%d %H:%M:%S %Z%z" # Current time in UTC now_utc = datetime.now(timezone('UTC')) print(now_utc.strftime(date)) # Convert to US/Pacific time zone now_pacific = now_utc.astimezone(timezone('US/Pacific')) print(now_pacific.strftime(date))
Output:
2019-10-31 01:15:33 UTC+0000 2019-10-30 18:15:33 PDT-0700
Here we get our standard time in UTC and later gets converted to US/Pacific timezone.
Also read,
Leave a Reply