gu_lv
gu_lv

Reputation: 65

Python convert string to datetime in variable formats

I am generating date and time information which is string from an API. The generated string is in your system's date/time format by default (Win 10 in my case). For example if you are using MM/DD/YYYY HH:MM:SS tt in your computer, the generated string would be something like "05/07/2019 06:00:00 AM".

For comparison purpose, I would then convert the string to datetime format by using datetime.datetime.strptime(i,"%m/%d/%Y %I:%M:%S %p"). This works prefectly fine, however if someone else whose system date/time format is different from' MM/DD/YYYY HH:MM:SS tt' runs my script, he would get a mismatch error as the string can no longer be converted by %m/%d/%Y %I:%M:%S %p.

So would it be possible to make the desired datetime format become a variable argument in the strptime function? Or even simpler, just make the format to be the same as the system's date/time format.

Upvotes: 2

Views: 690

Answers (1)

Piakkaa
Piakkaa

Reputation: 818

You can use try and except to fix this (although there might be another way)

try:
  datetime.datetime.strptime(i,"%m/%d/%Y %I:%M:%S %p")
except TypeError:
  try:
     datetime.datetime.strptime(i,"%d/%m/%Y %I:%M:%S %p")
  except:
     try:
         datetime.datetime.strptime(i,"%d/%m/%y %I:%M:%S %p")
# and so on....

Upvotes: 1

Related Questions