jeudi 28 décembre 2017

What is an efficient way to test a string for a specific datetime format like "m%/d%/Y%" in python 3.6?

In my pthon 3.6 application, from my input data I can receive datatimes in two different formats:

"datefield":"12/29/2017" or "datefield":"2017-12-31"

I need to make sure the that I can handle either datetime format and convert them to (or leave it in) the iso 8601 format. I want to do something like this:

#python pseudocode
import datetime
if datefield = "m%/d%/Y%":
  final_date = datetime.datetime.strptime(datefield, "%Y-%m-%d").strftime("%Y-%m-%d")
elif datefield = "%Y-%m-%d":
  final_date = datefield

The problem is I don't know how to check the datefield for a specific datetime format in that first if-statement in my pseudocode. I want a true or false back. I read through the python docs and some tutorials. I did see one or two obscure examples that used try-except blocks, but that doesn't seem like an efficient way to handle this.

Aucun commentaire:

Enregistrer un commentaire