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
Convert string to DateTime and vice-versa in Python
Python has extensive date and time manipulation capabilities. In this article, we'll see how a string with proper format can be converted to a datetime object and vice versa.
Converting String to DateTime with strptime()
The strptime() function from the datetime module can convert a string to datetime by taking appropriate format specifiers ?
import datetime
dt_str = 'September 19 2019 21:02:23 PM'
# Given date time string
print("Given date time:", dt_str)
print("Data Type:", type(dt_str))
# Define format specifiers
dtformat = '%B %d %Y %H:%M:%S %p'
# Convert string to datetime
datetime_val = datetime.datetime.strptime(dt_str, dtformat)
print("After converting to datetime:", datetime_val)
print("Data type:", type(datetime_val))
Given date time: September 19 2019 21:02:23 PM Data Type: <class 'str'> After converting to datetime: 2019-09-19 21:02:23 Data type: <class 'datetime.datetime'>
Converting DateTime to String with str()
The str() function converts its parameter to a string. Here we take a datetime value using datetime.today() and convert it to string ?
import datetime
# Get current datetime
current_dt = datetime.datetime.today()
print("Date time data type:", current_dt)
print("Data type:", type(current_dt))
# Convert datetime to string
dtstr = str(current_dt)
print("String Date time:", dtstr)
print("Data type:", type(dtstr))
Date time data type: 2020-05-18 11:09:40.986027 Data type: <class 'datetime.datetime'> String Date time: 2020-05-18 11:09:40.986027 Data type: <class 'str'>
Converting DateTime to String with strftime()
For more control over the output format, use strftime() to format datetime objects as strings ?
import datetime
datetime_val = datetime.datetime(2019, 9, 19, 21, 2, 23)
# Convert to formatted string
formatted_str = datetime_val.strftime('%B %d, %Y at %I:%M %p')
print("Formatted string:", formatted_str)
# Different format
date_only = datetime_val.strftime('%Y-%m-%d')
print("Date only:", date_only)
Formatted string: September 19, 2019 at 09:02 PM Date only: 2019-09-19
Common Format Specifiers
| Specifier | Description | Example |
|---|---|---|
%Y |
4-digit year | 2019 |
%B |
Full month name | September |
%d |
Day of month | 19 |
%H |
24-hour format | 21 |
%I |
12-hour format | 09 |
%p |
AM/PM | PM |
Conclusion
Use strptime() to convert strings to datetime objects and strftime() for formatted datetime-to-string conversion. The str() function provides basic datetime-to-string conversion with default formatting.
