Python - How to convert string to datetime object

By xngo on June 7, 2019

Converting a date string to a datetime object is a manner of using datetime.strptime(date_string, format) function. You only have to define your date string format pattern so that it can parsed correctly. A list of format code can be found at https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior.

#!/usr/bin/python3
# Description: How to convert string to date.
 
from datetime import datetime
 
str = '06/27/2019'
datetime_object = datetime.strptime(str, '%m/%d/%Y')
print(datetime_object)
 
str = 'Fri, May 17 2019'
datetime_object = datetime.strptime(str, '%a, %B %d %Y')
print(datetime_object)
 
str = '7-Jun-2019'
datetime_object = datetime.strptime(str, '%d-%b-%Y')
print(datetime_object)
 
str = 'Jun 1 2005 1:35:49PM'
datetime_object = datetime.strptime(str, '%b %d %Y %I:%M:%S%p')
print(datetime_object)
 
str = '2007-11-05T15:23:01Z'
datetime_object = datetime.strptime(str, '%Y-%m-%dT%H:%M:%SZ')
print(datetime_object)
 
# List of all format codes can be found at
#   https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

Output

Reference

  • https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime
  • https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.