Python Convert String into date and datetime example

This tutorial explains about

  • Parse string into a date in Python
  • Convert string object to datetime in Python

Convert String into a Date object

datetime library provides datetime class, strptime() takes string and format and returns date.

datetime.strptime(datestring, format)

datestring is a string that contains the date of numbers Here is an example

from datetime import datetime
str="022422"
date = datetime.strptime(str,'%m%d%y').date()
print(date) #2022-02-24

if str contains invalid data such as nonnumeric values, It throws an error. ValueError: time data 'abc' does not match format '%m%d%y'

How to parse String to DateTime Object

Multiple ways we can convert String to DateTime object

  • Use datetime library

datetime library contains strptime function, takes two parameters

  • string contains the date
  • format %b %d %Y %I:%M%p
    • %b: represents Month name, for example Jun
    • %d: day of the month with zero padding
    • %Y: year
    • %I: hour with zero padding
    • %M: Minute with zero padding
    • %p: AM or PM
import datetime

str1 = 'Aug 10 2023  10:44AM'
date1 = datetime.datetime.strptime(str1, '%b %d %Y %I:%M%p')

print(date1) # 2023-08-10 10:44:00
print(type(date1)) # <class 'datetime.datetime'>

str2 = 'Sep 11 2023 03:00PM'
date2 = datetime.datetime.strptime(
    str2, '%b %d %Y %I:%M%p')
print(date2) # 2023-09-11 15:00:00
print(type(date2)) # <class 'datetime.datetime'>
  • using DateParser library Install DateParser using the below command in a project
pip install dateparser
  • use the library in a code using the import line
  • dateparser.parse() takes the string object and converts to DateTime
import dateparser

str1 = 'Aug 10 2023  10:44AM'
date1 = dateparser.parse(str1)
print(date1) # 2023-08-10 10:44:00
print(type(date1)) # <class 'datetime.datetime'>

str2 = 'Sep 11 2023 03:00PM'
date2 = dateparser.parse(str2)
print(date2) # 2023-09-11 15:00:00
print(type(date2)) # <class 'datetime.datetime'>