Unix Timestamp, UTC And Their Conversions In Python!


Recently I started messing with Nidaba. Nidaba is a data analytics project devoted to analysing and making use of the freely available information on Stack Overflow, in particular when relating to the Python programming language. SO gives all time objects in  Unix time format. For analysis, it is required to convert it into human readable format to figure out the day it corresponds to. Let us take a look at UTC & Unix timestamps.

Coordinated Universal Time(UTC):

It is the primary time standard by which the world regulates clocks and time.

To get current UTC time in Python, You can use datetime module.
In [5]: import datetime

In [6]: datetime.datetime.now(datetime.timezone.utc)
Out[6]: datetime.datetime(2014, 11, 22, 14, 42, 21, 34435, tzinfo=datetime.timezone.utc)

Unix time / POSIX time / Epoch time: 

It is a system for describing instants in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds.

To get Unix timestamp, you can use time module.
In [8]: import time

In [9]: time.time()
Out[9]: 1416667432.5664258

In [10]: int(time.time())
Out[10]: 1416667766
If You are using Pyhon 3.4, you can use timestamp function to convert it
In [13]: datetime.datetime.utcnow().timestamp()
Out[13]: 1416649608.58369

Conversions:

To convert Unix timestamp to UTC You can use utcfromtimestamp function.
In [21]: datetime.datetime.utcfromtimestamp(1416668401)
Out[21]: datetime.datetime(2014, 11, 22, 15, 0, 1)
To convert UTC time object to Unix time, you can use strftime function.
In [38]: dt = datetime.datetime.now()

In [39]: dt.strftime("%s")
Out[39]: '1416668938'
Alternatively You can use calendar.timegen function also.
In [46]: import calendar

In [47]: dt = datetime.datetime.utcnow()

In [48]: calendar.timegm(dt.utctimetuple())
Out[48]: 1416669150


I am Chillar Anand. I daydream a lot and write about the things that interest me here. You can read more about this blog here.

See all articles

RSS Feed for the blog

Edit this page