- How To Convert Timestamp To Date and Time in Python
- Using module datetime
- Using module time
- Formatting
- Tags
- Related Articles
- 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
How To Convert Timestamp To Date and Time in Python
There are multiple ways how you can convert timestamp to human readable form in Python. For this conversion you may either use module datetime or time.
Using module datetime
Module datetime provides classes for manipulating date and time in more object oriented way.
import datetime readable = datetime.datetime.fromtimestamp(1690408719).isoformat() print(readable) # 2023-07-26T23:58:39+02:00
Using module time
Another possibility to use function ctime from module time .
import time readable = time.ctime(1690408719) # Wed Jul 26 23:58:39 2023
Formatting
For custom human readable format you may use function strftime .
import time ts = time.gmtime() print(time.strftime("%Y-%m-%d %H:%M:%S", ts)) # 2023-07-26 23:58:39 print(time.strftime("%x %X", ts)) # 07/26/23 23:58:39 # Iso Format print(time.strftime("%c", ts)) # Wed Jul 26 23:58:39 2023 # Unix timestamp print(time.strftime("%s", ts)) # 1690408719
Directive | Meaning |
---|---|
%a | Locale’s abbreviated weekday name. |
%A | Locale’s full weekday name. |
%b | Locale’s abbreviated month name. |
%B | Locale’s full month name. |
%c | Locale’s appropriate date and time representation. |
%d | Day of the month as a decimal number [01,31]. |
%H | Hour (24-hour clock) as a decimal number [00,23]. |
%I | Hour (12-hour clock) as a decimal number [01,12]. |
%j | Day of the year as a decimal number [001,366]. |
%m | Month as a decimal number [01,12]. |
%M | Minute as a decimal number [00,59]. |
%p | Locale’s equivalent of either AM or PM. |
%S | Second as a decimal number [00,61]. |
%U | Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. |
%w | Weekday as a decimal number [0(Sunday),6]. |
%W | Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. |
%x | Locale’s appropriate date representation. |
%X | Locale’s appropriate time representation. |
%y | Year without century as a decimal number [00,99]. |
%Y | Year with century as a decimal number. |
%Z | Time zone name (no characters if no time zone exists). |
%% | A literal ‘%’ character. |
Tags
Related Articles
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.