Home > Software design >  Datetime conversion generic approach
Datetime conversion generic approach

Time:02-24

I have the following dates:

4/29/2020
5/7/2020
9/10/2020
10/5/2020
11/20/2020

The dates extracted from Oracle are correctly read as datetime objects in Python. However, when I manually add dates to the list in Excel, the program sees the date as string and crashes.

invalid input for query argument $1: '9/10/2020' (expected a datetime.date or datetime.datetime instance, got 'str')

This is what I am doing:

if isinstance(my_date,str):
             my_date = date.fromisoformat(my_date)

It's not working. Is there a way to automatically convert a date in any format to datetime object? Thanks!

CodePudding user response:

Yes there is : datetime.strptime

You can find documentation on how to use it here : https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

CodePudding user response:

You can convert your code to something like this:

from datetime import datetime

if isinstance(my_date,str):
             my_date = datetime.strptime(my_date, '%m/%d/%Y')
  • Related