Convert Integer to datetime in Python (2 Examples)

 

In this tutorial, you’ll learn how to convert an integer timestamp into a datetime using the Python programming language.

The tutorial includes the following sections:

Let’s dive into it!

 

Library Imports & Data Initialization

Firstly, we need to import datetime from the datetime module, pytz and the pandas library.

from datetime import datetime
import pytz
import pandas as pd

To avoid timezone complications, we will initialize a timezone object.

timezone = pytz.timezone('UTC')

The created UTC timezone object will be used to generate the sample datetime object and a timestamp.

sample_date = datetime(2018, 6, 15, 18, 12, 45, 15, tzinfo=timezone)
print(sample_date)
ts = sample_date.timestamp()
print(ts) 
# 1529086365.000015

 

Example 1: Using fromtimestamp() functions

The utcfromtimestamp() function will return the datetime for the UTC timezone.

dt = datetime.utcfromtimestamp(ts)
print(dt) 
# 2018-06-15 16:12:45.000015

The fromtimestamp() function will return the datetime for the given timezone.

dt2 = datetime.fromtimestamp(ts, tz=timezone)
print(dt2)
# 2018-06-15 18:12:45.000015+00:00

Note: If the timezone parameter, tz, isn’t set; then the timezone for the system will be used automatically.

 

Example 2: Using pandas to_datetime() function

There is also the to_datetime() function of the pandas library to convert timestamps into datetime objects. Since our timestamp’s integer part is in seconds, we will set the time unit as ‘s’.

dt3 = pd.to_datetime(ts, unit='s')
print(dt3)
# 2018-06-15 18:12:45.000015104

To show how the unit parameter can be utilized, we can multiply our timestamp with the value 1000 to make the integer part be in microseconds and set the unit as ‘ms’ and then get the datetime again.

dt4 = pd.to_datetime(ts*1000, unit='ms')
print(dt4)

As you can see, both datetime results are the same.

 

Video, Further Resources & Summary

Do you need more explanations on how to convert an integer timestamp into a datetime? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

 

The YouTube video will be added soon.

 

Furthermore, you could have a look at some other tutorials on Statistics Globe:

This post has shown how to transform an integer timestamp into a datetime. In case you have further questions, you may leave us a comment below.

 

Ömer Ekiz Informatics Expert

This page was created in collaboration with Ömer Ekiz. You may have a look at Ömer’s author page to read more about his academic background and the other articles he has written for Statistics Globe.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top