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.

Related Posts

  • Convert datetime to date in Python
    20 June

    Convert datetime to date in Python

    Table of ContentsUsing the date() function to convert datetime to date in Python.Using the dt.date function in pandas to convert datetime to date in Python. Date and time in Python are not a pre-defined data type itself. The datetime module can be imported to the Python code and it provides classes used that manipulate and […]

  • Convert unix timestamp to datetime in Python
    21 May

    Convert Unix timestamp to DateTime in python

    Table of ContentsUsing fromtimestamp() FunctionUsing strftime() FunctionUsing to_datetime() Function A UNIX timestamp is defined as the several numbers of seconds between a particular date and the Epoch i.e January 1, 1970 at UTC. In this tutorial, we will see some methods by which we can convert a UNIX timestamp to DateTime in Python. Using fromtimestamp() […]

  • Last day of month in Python
    20 May

    Get last day of month in Python

    Table of ContentsUsing the calendar.monthrange() functionUsing the dateutil.relativedelta() functionUsing the datetime moduleUsing the pandas.end_time() functionUsing the pandas.date_range() In this article, we will discuss how to find the last day of the month in Python using different modules. Using the calendar.monthrange() function The monthrange() function is used to return a tuple containing the first weekday of […]

  • Add days to date in Python
    19 May

    Add days to date in Python

    Table of ContentsUsing datetime.timedelta() FunctionAdd one day to date using datetime.timedelta()Using timedelta method from datetime moduleUsing Pandas Module In python, we deal with a lot of date and time-related problems. There is no specific data type for date and time still there is a lot of manipulation done on them in python. We can perform […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.