Converting string into datetime in Python

Let\’s see how to convert a string with date and time information into a datetime object in Python.

This conversion can be done using the datetime.strptime() method.

First Example

The first example expects a string with the following format:

  • %b: Month as locale’s abbreviated name.
  • %d: Day of the month as a zero-padded decimal number.
  • %Y: Year with century as a decimal number.
  • %I: Hour (12-hour clock) as a zero-padded decimal number.
  • %M: Minute as a zero-padded decimal number.
  • %p: Locale’s equivalent of either AM or PM.

Notice the \’:\’ separating the hours from the minutes in the format.

from datetime import datetime

datetime_str = 'Apr 22 2020 9:28PM'

datetime_obj = datetime.strptime(datetime_str, '%b %d %Y %I:%M%p')

print(datetime_obj)
2020-04-22 21:28:00

Second Example

The second example expects a string with the following format:

  • %a: Weekday as locale’s abbreviated name.
  • %b: Month as locale’s abbreviated name.
  • %d: Day of the month as a zero-padded decimal number.
  • %H: Hour (24-hour clock) as a zero-padded decimal number.
  • %M: Minute as a zero-padded decimal number.
  • %S: Second as a zero-padded decimal number.
  • %Y: Year with century as a decimal number.
from datetime import datetime

datetime_str = 'Wed Apr 22 21:28:02 2020'

datetime_obj = datetime.strptime(datetime_str, '%a %b %d %H:%M:%S %Y')

print(datetime_obj)
2020-04-22 21:28:02

You can check the official documentation for other Format Codes to parse different string formats to datetime.

Watch this Content