3

I have a hacky solution but it feels completely wrong. I'm simply doing a compare of dates (one starts as a string which I convert) and my start_date sometimes contains milliseconds. I was running this:

from datetime import datetime

def main():

    start_date = "2019-05-22 20:00:02.1231"

    try:
        start_date = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S.%f')
        print("i have milliseconds")
    except:
        start_date = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S')
        print("no milliseconds")

    if start_date < datetime.now():
        print("yipee")

if __name__ == "__main__":
    main()

There is also a chance that there are no seconds, so I could have:

start_date = "2019-05-22 20:00"

I could add another try but I think I'm just missing a simple solution. I found this: python strptime format with optional bits which suggests use try so I would use try twice in this case, so is that the answer?

sniperd
  • 5,124
  • 6
  • 28
  • 44
  • 1
    Yes, that's the answer. – pault May 29 '19 at 19:19
  • 1
    So just use `try` twice. Okie dokie, I was hoping there was some super duper clever :) – sniperd May 29 '19 at 19:20
  • Also related: [Parsing Timestamp in Python](https://stackoverflow.com/questions/48408946/parsing-timestamp-in-python/48409213#48409213) – pault May 29 '19 at 19:21
  • There's also the `dateutil` library: [Convert “unknown format” strings to datetime objects?](https://stackoverflow.com/questions/13258554/convert-unknown-format-strings-to-datetime-objects) or you *could* use regular expressions. – pault May 29 '19 at 19:24

0 Answers0