Converting a String into Datetime Object in Python 3

Last updated on November 4, 2021 Pennywise Loading... Post a comment

You can use the datetime.strptime function to convert a string into a datetime object in Python 3.

Example:

from datetime import datetime

s1 = '20211104'
s2 = '2021/12/09'
s3 = '2022-10-28 04:12:31'

dt1 = datetime.strptime(s1, '%Y%m%d')
dt2 = datetime.strptime(s2, '%Y/%m/%d')
dt3 = datetime.strptime(s3, '%Y-%m-%d %H:%M:%S')

dt1, dt2, dt3

Output:

datetime.datetime(2021, 11, 4, 0, 0),
datetime.datetime(2021, 12, 9, 0, 0),
datetime.datetime(2022, 10, 28, 4, 12, 31)

The example above shows you how strings can be parsed into datetime objects. If you’d like to explore more new and interesting stuff about modern Python, take a look at the following articles:

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like