Home > Back-end >  Correct format for converting french date from string to datetime?
Correct format for converting french date from string to datetime?

Time:10-02

I'm trying to convert strings to date, but it's not working for some dates in french. Like in the example below :

myDate = datetime.strptime(dateInStringFormat, "%A %d %B %Y  %H:%M:%S")

Result with the error : time data '"jeudi 8 septembre 2022 13:51:13"' does not match format '%A %d %B %Y %H:%M:%S'.

I've tried a lot a variations in the format I can't make it work, anyone know how to do this please ?

CodePudding user response:

I had the same problem once and found a module called dateparser to do that:

import dateparser
d = dateparser.parse("jeudi 8 septembre 2022 13:51:13")

d is now

datetime.datetime(2022, 9, 8, 13, 51, 13)

CodePudding user response:

try:

import locale
import datetime
locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')

dateInStringFormat = "jeudi 8 septembre 2022 13:51:13"
myDate = datetime.datetime.strptime(dateInStringFormat, "%A %d %B %Y %H:%M:%S")

print(myDate)
# 2022-09-08 13:51:13

myDate
# datetime.datetime(2022, 9, 8, 13, 51, 13)
  • Related