Search code examples
pythonstrptime

Python Strptime Occasionally Missing Microseconds


I have data being passed in coming in with the format %Y-%m-%d %H:%M:%S.%f.

So I work with the data based on that structure and once a blue moon something goes wrong. So I started dumping it out when something breaks and I noticed the microseconds at the end were missing.

I'm presuming this means it was dead on 0 and it's not sending it at all instead of sending .000000

Of the top of my head I could split it by "." and count the len each time. Split it into %Y-%m-%d %H:%M:%S if it's below the length of having the microseconds but is there a neater way of dealing with milliseconds missing and replacing it with 000's?

I caught the dump of the milliseconds missing and a ValueError throwing right after it. I didn't think about it I guess I assumed it'd sent .000000 but it seems like the most obvious problem http://puu.sh/n4BLT/9b3fb473fb.png


Solution

  • Why not just try both?

    def parse_txt(txt):
        try: 
            return datetime.datetime.strptime(txt, "%Y-%m-%d %H:%M:%S.%f")
        except ValueError:
            return datetime.datetime.strptime(txt, "%Y-%m-%d %H:%M:%S")
    
    parse_txt("2001-01-01 01:01:01")    # => datetime.datetime(2001, 1, 1, 1, 1, 1)