- Unix Timestamp to datetime in Python
- What is Python Epoch time?
- How to get Python current Timestamp/epoch?
- Some format code in Python
- Program to Get Python current epoch/timestamp from datetime
- Program Example
- 2. Python epoch/timestamp to dateTime with UTC
- Program to epoch time to dateTime with UTC
- 3. Python epoch/Timestamp milleseconds to Datetime
- Program Example
- 4. Python unix timestamp/epoch to datetime string
- Program Example
- 5. Time Module to Unix timestamp to datetime string
- Program Example
- 6. Unix timestamp to datetime Python Pandas
- Program Example
- Summary
- Easily Convert Unix time to Datetime in Python
- What is the Unix Time Format?
- What is Datetime Module, and What are Datetime Objects?
- How to Convert Unix Time to a Python Datetime Object?
- How to Convert Datetime Object to Unix time in Python
- How To Convert Unix Time To Datetime in Pandas Dataframes
- How To Convert a Unix timestamp in Nanoseconds to Date and Time
- How To Convert Datetime Object To a Specific Timezone
- FAQs on Python Convert UNIX time to datetime
- Conclusion
- Convert Unix timestamp to DateTime in python
- Using fromtimestamp() Function
- Using strftime() Function
- Using to_datetime() Function
Unix Timestamp to datetime in Python
In this post, we are going to learn how to convert Unix Timestamp to datetime in Python with examples. First, we will get the current epoch in Python and then use this in our examples to use it convert the UNIX timestamp to datetime
What is Python Epoch time?
The Unix time is also known as epoch time. It represents the time passed since Jan 1, 1970. In Python date is not a built-in datatype, the datetime Module is used to manipulate Date and Time.
To convert Python Unix epoch/timestamp to datetime, Let us understand how to get Unix current Timestamp/epoch.
How to get Python current Timestamp/epoch?
- Get the current date and time using datetime.now() Method.
- Get the Timestamp/epoch from datetime using timestamp() method.
- Convert timestamp to timestamp milliseconds by multiple 1000
In Our all examples, we are using the hard code value of epoch time. If you need to use the dynamic value of the timestamp, then use the one that we have calculated in the given below example.
Some format code in Python
- %Y : four-digit year
- %y : two digit year
- %m: Month
- %d: date
- %H : for hours
- %M : for minutes
- %S: for second
- %f : for milliseconds
Program to Get Python current epoch/timestamp from datetime
from datetime import datetime timestamp = datetime.now().timestamp() print("current timestamp =", timestamp) print("datetime to epoch millisecond:",timestamp*1000)
Program Example
from datetime import datetime unix_timestamp = datetime.now().timestamp() # Getting date and time in local time datetime_obj = datetime.fromtimestamp(int(unix_timestamp)) print('DateTime default Format :',datetime_obj) print('Custome formatted DateTime:',datetime_obj.strftime("%d.%m.%y %H:%M:%S"))
DateTime default Format : 2021-07-31 06:04:52 31.07.21 06:04:52
2. Python epoch/timestamp to dateTime with UTC
In this example, the Datetime module’s utcfromtimestamp() function is used to get the epoch time to datetime with UTC.Finally, The datetime class strftime() method is used to convert datetime to a specific format as per need.
Program to epoch time to dateTime with UTC
from datetime import datetime unix_timestamp = "1627671140" # Getting the date and time in UTC datetime_obj = datetime.utcfromtimestamp(int(unix_timestamp)) print(datetime_obj.strftime("%d.%m.%y %H:%M:%S"))
3. Python epoch/Timestamp milleseconds to Datetime
In this example, we are repeating the same steps as mentioned in the above examples. We are converting Python epoch milliseconds to Datetime.
Program Example
#Python 3 Progaram to epoch milleseconds to Datetime millesecods import datetime millseconds = 1627673330000/ 1000.0 datetime_obj = datetime.datetime.fromtimestamp(millseconds).strftime('%Y-%m-%d %H:%M:%S.%f') print(datetime_obj)
4. Python unix timestamp/epoch to datetime string
Using Datetime module fromtimestamp() function to convert epoch time/Unix timestamp to datetime and strftime() function to convert datetime to string.
Program Example
import datetime unix_time = 1627675321 datetime_obj = datetime.datetime.fromtimestamp(unix_time ).strftime('%Y-%m-%d %H:%M:%S') print(datetime_obj) print(type(datetime_obj))
5. Time Module to Unix timestamp to datetime string
The Python time module strftime() function is used in this example to convert unix timestamp/epoch to datetime.
The first parameter to this function is format code and another is the Unix timestamp.
Program Example
#Python3 program to convert unix timestamp to datetime string import time time_epoch = 1627675321 time_obj = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time_epoch)) print("epoch to datetime string:", time_obj) print(type(time_obj))
epoch to datetime string: 2021-07-31 01:32:01
6. Unix timestamp to datetime Python Pandas
In this example, we are using the Pandas module to convert Unix timestamp to datetime.
First, import the panda’s module using import pandas as pd. Then using the pandas to_datetime() function to convert Unix timestamp/epoch to datetime. Finally printing the result using the print() method.
Program Example
import pandas as pd time_epoch = 1627675321 print('unix timestamp to datetime:',pd.to_datetime(time_epoch, unit='s'))
unix timestamp to datetime : 2021-07-30 20:02:01
Summary
- In this post, we have learned how to convert Unix Timestamp to datetime in Python.First we get the current epoch/timestamp .
- Then explained with different ways that includes Convert Python epoch to datetime,Python epoch/Timestamp milleseconds to Datetime milliseconds,Python unix timestamp/epoch to datetime string using datetime module fromtimestamp() and strftime() method to datetime.
Easily Convert Unix time to Datetime in Python
In this article, we will be discussing Unix time and how to convert Unix time to datetime in Python. Before we review the Python implementations, let’s discuss what the concept of Unix time is.
In the field of computing, Unix time is a digital timestamp. Unix time represents the number of seconds passed since the Unix epoch without including leap seconds.
What is the Unix epoch? This epoch is nothing but a date and time set by Unix engineers to establish the start of Unix time. The date is New Year’s Day, 1970, at exactly 00:00:00 UTC. Therefore, the total number of seconds since January 1st, 1970, 00:00:00 UTC, is the current Unix time.
What is the Unix Time Format?
A single signed number represents Unix time which increases each second.
As of writing this article, the UNIX time is: 1661324766
This means 1,661,324,766 seconds have passed since Unix Epoch.
What is Datetime Module, and What are Datetime Objects?
Python datetime module is a part of the Python standard library under the “datatypes” category. The DateModule provides multiple classes to handle dates and times in different formats.
A Datetime object is an instance created within the Python class. datetime . datetime . In the datetime module, there are 2 types of objects
- Naive Objects – Doesn’t contain timezone information
- Aware Objects – A localized datetime object based on a timezone.
How to Convert Unix Time to a Python Datetime Object?
As we’ve discussed, we use the Datetime module to handle dates and times. With the help of the fromtimestamp() function, we can convert Unix time to a datetime object in Python. Within the function, pass Unix time as an argument.
Let’s look at the following implementation:
import datetime unixToDatetime = datetime.datetime.fromtimestamp(1661324766) # Unix Time print(unixToDatetime)
Output
How to Convert Datetime Object to Unix time in Python
Using the timestamp() function from the Datetime module, we can convert the Datetime object to Unix time. The function will return a float value representing the Unix time.
Let’s use the datetime object ( unixToDatetime ) created in the previous demonstration
datetimeToUnix = unixToDatetime.timestamp() print(datetimeToUnix)
How To Convert Unix Time To Datetime in Pandas Dataframes
Let’s say a data frame consists of a column containing Unix time values. How do we convert the values of this column into standard date and time?
Using the to_datetime() function from the Datetime module, we can solve our problem.
Here’s our sample data frame(df):
date price 0 1349720105 2300.23 1 1349806505 8776.11 2 1349892905 9009.33 3 1350065705 2223.22
Let’s see how the function is implemented in this scenario:
import pandas as pd from datetime import datetime df df['date'] = pd.to_datetime(df['date'],unit='s') # Changing the values of the column
Output
date price 0 2012-10-08 18:15:05 2300.23 1 2012-10-09 18:15:05 8776.11 2 2012-10-10 18:15:05 9009.33 3 2012-10-12 18:15:05 2223.22
Observe that all values in the “Date” column are now Datetime objects.
How To Convert a Unix timestamp in Nanoseconds to Date and Time
By converting the Unix time to a datetime object, we can present it in a human-readable format. Let’s look at the following implementation
from datetime import datetime # flooring the value by 1 billion readableDt = datetime.fromtimestamp( 1220287113082844499 // 1000000000) readableDt
Output
datetime.datetime(2008, 9, 1, 16, 38, 33)
Tip: To format the result in YYYY/MM/DD H: M: S, use the . strftime() method
How To Convert Datetime Object To a Specific Timezone
Time Zone conversion is an essential feature that this module provides. Using the .astimezone function, we can achieve such requirements.
The following program converts from UTC to America/Los Angeles.
from datetime import datetime, timezone, ZoneInfo dt_UTC = datetime.now(timezone.utc) dt_LA = dt_UTC.astimezone(tz=datetime.ZoneInfo("America/Los_Angeles")) print(dt_LA)
Output
FAQs on Python Convert UNIX time to datetime
You can display Unix time as normal time by converting it to a Datetime object. Use the fromtimestamp() function.
Unix time is represented as a single signed value that denotes the number of seconds since the Unix Epoch.
First, convert the Unix timestamp to a Datetime object using fromtimestamp() . Then, convert the default timezone of the Datetime object to UTC using astimezone() .
Conclusion
In this article, we have discussed the concept of UNIX time and its origin. Unix time is the number of seconds since the Unix Epoch. The Unix Epoch is a date set by UNIX engineers to represent the start of Unix time. Unix time is represented within a single signed value.
We have discussed techniques to convert Unix times to Datetime objects and vice-versa. We have also discussed techniques to convert Unix time values in Pandas data frames.
Convert Unix timestamp to DateTime in python
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() Function
DateTime module in python is used to deal with the date and time-related problems in python.
One of the functions in this module is the fromtimestamp() function. This function returns the time that is expressed as seconds i.e UNIX timestamp.
Here, we first import the datetime class from the datetime module. Then we store the UNIX value object in a variable. After that, we use the datetime.fromtimestamp() function that will get us the time and date. Finally, we print the unix_val variable.
To get the current timestamp, we use the now() function from the datetime module.
To convert this again to DateTime, we use the same code from example 1.
Using strftime() Function
Another function in the datetime module is the strftime() function. This function helps in returning the DateTime in a specific form. To convert the date and time objects to their string representation, this function is generally used.
In the above code, %d, %m, %Y, %H, %M and %S are called format codes which represent days, month, year, hour, minutes, and seconds respectively. In this code also, fromtimestamp() is used to return the time that is expressing in the UNIX timestamp.
Using to_datetime() Function
This function comes under the Pandas library in python. Pandas is one of the most common libraries in python. This library helps in manipulating and analyze data and is widely used in the field of data science.
The to_datatime() of the Pandas library helps in converting a Unix timestamp to DateTime in Python.