2

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.

gu_lv
  • 65
  • 10
  • check this link https://stackoverflow.com/questions/7065164/how-to-make-an-unaware-datetime-timezone-aware-in-python – Vaibhav May 07 '19 at 07:32
  • You should generate an unambiguous string, that is choose a format once for all. (In IT world, "unambiguous" means often "US"). Workaround: ship the format with the string if possible. – jferard May 07 '19 at 08:15

1 Answers1

1

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....
Piakkaa
  • 740
  • 6
  • 12