Converting a String into Datetime Object in Python 3

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:
- How to Check Whether an Object is Iterable in Python 3
- Using the isinstance() function in Python 3
- Python filter() function examples
- Python program to count all capital letters in a string
- Examples of numpy.linspace() in Python
You can also check out our Machine Learning category page or Python category page for more tutorials and examples.
Subscribe
0 Comments