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.

2
  • check this link stackoverflow.com/questions/7065164/… Commented May 7, 2019 at 7: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. Commented May 7, 2019 at 8:15

1 Answer 1

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....
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply, that is what I did so far. However there are way more than these 2 kinds of formats.
You can also keep going like try: something except: try: something except:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.