Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert timestamp string to datetime object in Python?
In many real-world applications, timestamps are used to represent dates and times, but they are not human-readable. To make them understandable or use them in various datetime manipulations, it's essential to convert them into Python's datetime object.
Python's datetime module provides multiple functions to convert timestamps to datetime objects. Below are the various methods to accomplish this task ?
- Using datetime.fromtimestamp() Function
- Using datetime.fromtimestamp() & strftime()
- Using datetime.strptime() Function
- Parsing Mixed Text Using strptime() Function
Using datetime.fromtimestamp() Function
To obtain a date from a UNIX timestamp, use the datetime module's fromtimestamp() function. This function accepts a timestamp as input and returns the datetime object corresponding to that timestamp.
Syntax
The following is the syntax for the fromtimestamp() function ?
fromtimestamp(timestamp, tz=None)
Example
The following program converts the timestamp to a datetime object using datetime.fromtimestamp() function ?
from datetime import datetime
timestamp_string = 1345612072
# Converting timestamp to DateTime object
datetime_object = datetime.fromtimestamp(timestamp_string)
# printing resultant datetime object
print("Resultant datetime object:", datetime_object)
print("Type of datetime object:", type(datetime_object))
Following is the output of the above code ?
Resultant datetime object: 2012-08-22 05:07:52 Type of datetime object: <class 'datetime.datetime'>
Using datetime.fromtimestamp() & strftime()
This method also starts with converting a timestamp to a datetime object using fromtimestamp(). But instead of returning a datetime object, it formats the output using the strftime() function into a specific string representation.
The strftime() function returns a formatted date and time. It accepts a format string that you can use to get the result you want. The following are the most commonly used directives ?
| Directive | Meaning |
|---|---|
| %Y | Year with century as a decimal number |
| %m | Month as a decimal number [01,12] |
| %d | Day of the month as a decimal number [01,31] |
| %H | Hour (24-hour clock) as a decimal number [00,23] |
| %M | Minutes as a decimal number [00,59] |
| %S | Second as a decimal number [00,61] |
| %B | Full month name |
| %A | Full weekday name |
Example
The following program converts the timestamp to a datetime object using datetime.fromtimestamp() function and formats it using strftime() function ?
from datetime import datetime
timestamp_string = 1345612072
# Converting timestamp string to datetime object and formatting it
datetime_object = datetime.fromtimestamp(timestamp_string).strftime('%d-%m-%y')
# printing resultant datetime object
print("Resultant datetime object:", datetime_object)
print("Type of datetime object:", type(datetime_object))
Following is the output of the above code ?
Resultant datetime object: 22-08-12 Type of datetime object: <class 'str'>
Using datetime.strptime() Function
The datetime.strptime() converts a string representing a date and time into a datetime object. This method is useful when we know the format of a timestamp string. The strptime() function parses the string and returns a datetime object based on the given format.
Example
The following program converts the timestamp string to a datetime object using datetime.strptime() function ?
from datetime import datetime timestamp_string = '2013-06-09T11::12::40.356237' format = '%Y-%m-%dT%H::%M::%S.%f' datetime_object = datetime.strptime(timestamp_string, format) # printing the resultant datetime object print(datetime_object) print(type(datetime_object))
Following is the output of the above code ?
2013-06-09 11:12:40.356237 <class 'datetime.datetime'>
Parsing Mixed Text Using strptime() Function
Sometimes, dates and times appear as part of full sentences or regular text. To convert a timestamp to a datetime object with format codes, we can handle mixed text scenarios.
In such cases, Python's strptime() function will extract and convert these into proper date-time objects by matching the pattern of the sentence.
Example
The following program converts a timestamp in the input mixed text string to a datetime object using datetime.strptime() function ?
from datetime import datetime
textString = "I was born on March 14th 2020 at 4 PM"
# Converting timestamp in the input mixed text string to
# datetime object and formatting it
datetime_object = datetime.strptime(textString, 'I was born on %B %dth %Y at %I %p')
# printing resultant datetime object
print("Resultant datetime object:", datetime_object)
print("Type of datetime object:", type(datetime_object))
Following is the output of the above code ?
Resultant datetime object: 2020-03-14 16:00:00 Type of datetime object: <class 'datetime.datetime'>
Conclusion
Python provides multiple ways to convert timestamp strings to datetime objects. Use fromtimestamp() for UNIX timestamps, strptime() for formatted timestamp strings, and combine with strftime() for custom formatting output.
