Convert epoch to datetime in python

Epoch to datetime in Python

Epoch time refers to the time elapsed since time was started measuring on January 1, 1970. Usually, it is measured in seconds. It is also known as UNIX time.

In this article, we will convert this epoch time to datetime object in Python.

First, let us understand what this datetime is. Python offers a module named datetime which has different classes and functions to process the date and time. The datetime object can be used to store some date and time, with the time zone if required, based on the desired format.

Using the datetime.fromtimestamp() function to convert epoch to datetime

To get the date and time from the given epoch time in a datetime object, we use the datetime.fromtimestamp() function.

See the following code.

Output:

1976-03-14 21:51:01

In the above example, we returned the given date and time using the provided epoch time. Also, note that we printed the type of the final result.

We can also specify the time zone for this returned date and time. For this, we will also import the timezone class from the datetime module.

See the code below.

Output:

1976-03-14 16:21:01+00:00

In the above example, timezone.utc produced the final result with UTC time zone offset. Alternatively, we can also use the utcfromtimezone() function to get the same result. This works for Python 3 only. For Python 2 users, the pytz.timezone method will do the same.

One thing to remember while using these functions is that the fromtimestamp() and utcfromtimestamp() functions will fail on the Windows platform for dates before January 1, 1970. However, negative UNIX timestamps seem to work on the UNIX platforms.

To work around this, we can use utc_time = datetime(1970,1,1) + timedelta(seconds=timestamp).

Now, let us understand how to get the final result in string and based on our required format.

For example, if we wish to get the final result as a string in some format, we can use the strftime() function. We can specify the required format in the function.

For example,

Output:

14-03-1976 16:21:01

Note the format specified in the function, we can alter this based on our needs by accessing different parts of the datetime object using the % operator.

Alternatively, we can also use the isoformat() function with this as it returns the date and time string separated by a given separator. The separator character is provided using the sep parameter. Also, we can use the timespec parameter to format the final time.

See the code below.

Output:

1976-03-14|16:21:01+00:00

Using the pandas.to_datetime() function to convert epoch to datetime in Python

Now, we know that the pandas DataFrame frequently has columns that store date values. For this, the pandas module is equipped with functionalities to work with the date and time values. The pd.to_datetime() function can be used to convert a column or a series object containing epoch time to readable date and time values in datetime type format. We can also specify the unit of the epoch time using the unit parameter.

For example,

Output:

0 1975-09-29 14:20:22
1 1978-08-06 00:47:52
2 1982-01-30 10:00:22
Name: date, dtype: datetime64[ns]

In the above example, we converted the date column to datetime using the to_datetime() function.

That’s all about how to convert epoch to datetime in Python.

Was this post helpful?

Related Posts

  • 18 May

    Get Hour from datetime in Python

    Table of ContentsHow to get hour from datetime in Python?Using the time() function and manually slicing out the hour part to get hour from datetime in Python.Using the % operator along with the datetime.hour attribute to get hour from datetime in Python.Using the format() function along with the datetime.hour attribute to get hour from datetime […]

  • 18 May

    Convert Month Name to Number in Python

    Table of ContentsHow to convert month name to number in Python?Creating a user-defined function and utilizing it to convert month name to number in Python.Using the calendar module to create a dictionary and utilize it to convert month name to number in Python.Using dict comprehension and the calendar module to convert month name to number […]

  • 18 May

    Add Hours to datetime in Python

    Table of Contentsdatetime in PythonWays to add hours to datetime in PythonUsing the datetime.Hour Attribute to Add Hours to datetime in PythonUsing the datetime.timedelta object to add hours to datetime in PythonUsing the dateutil.Relativedelta Object to Add Hours to datetime in PythonUsing the pandas.Date Offset() Function to Add Hours to datetime in PythonUsing the arrow.shift() […]

  • Format Date to YYYYMMDD in Python
    03 March

    Format Date to YYYYMMDD in Python

    Table of ContentsDate formats in PythonHow to convert date to YYYYMMDD format in PythonUsing datetime.strftime() Function to Format Date to YYYYMMDD in PythonUsing datetime.date Object to Format Date to YYYYMMDD in PythonUsing date.isoformat() Function to Format Date to YYYYMMDD in PythonUsing arrow.format() Function to Format Date to YYYYMMDD in PythonUsing pendulum.to_date_string() Function to Format Date […]

  • Get today's date in Python
    03 March

    Get Today’s Date in Python

    Table of ContentsDate and Time objects in PythonGet Today’s Date in PythonUsing date.today() Function to Get Today’s Date in PythonUsing datetime.today() and datetime.strftime() Functions to Get Today’s Date in PythonUsing datetime.now() Function to Get Today’s Date in PythonUsing strftime() Function to Get Today’s Date in PythonUsing time.strftime() Function to Get Today’s Date in PythonUsing arrow.now() […]

  • Add seconds to datetime in Python
    11 February

    Add Seconds to Datetime in Python

    Table of ContentsDate and Time in PythonWays to add seconds to datetime object in PythonUsing the datetime.timedelta object to add seconds to datetime in PythonUsing the datetime.time.second attribute to add seconds to datetime in PythonUsing the arrow.shift() function to add seconds to arrow object in PythonConclusionWas this post helpful? Date and Time in Python Python […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.