Home > Software design >  Identify if datetime is in timespec='milliseconds'
Identify if datetime is in timespec='milliseconds'

Time:09-30

I have following datetimes:

a = "2018-07-13T00:00:00 00:00"
b = "2018-07-13T00:00:00.000000 00:00"

I want to check if a datetime has timespec='milliseconds'. So my function should return False for a and True for b Any ideas how to solve this?

CodePudding user response:

Assuming you have strings as in the question.

If you only have the two formats above, you could only check the length:

def has_ms(s):
    return len(s) == 32

You could also perform a complete match of the format in b:

def is_ms_strict_format(s):
    import re
    return bool(re.match(r'\d{4}-\d{2}-\d{2}T(\d{2}:){2}\d{2}\.\d{6}\ \d{2}:\d{2}', s))

examples:

>>> has_ms(a)
False
>>> has_ms(b)
True
>>> is_ms_strict_format(a)
False
>>> is_ms_strict_format(b)
True

CodePudding user response:

Assuming you are dealing with datetime string in iso format

from datetime import datetime

def has_microseconds(dt):
    return not datetime.fromisoformat(dt).isoformat(timespec='seconds') == dt

a = "2018-07-13T00:00:00 00:00" # seconds
b = "2018-07-13T00:00:00.000000 00:00" # microseconds
c = "2018-07-13T00:00:00.000 00:00" # milliseconds

print(has_microseconds(a))
print(has_microseconds(b))
print(has_microseconds(c))

output

False
True
True

Note this will not work (needs refinement) if the string is in iso format, but has only hours [and minutes] but not seconds.

UPDATE: Here is function that will return exact timespec given iso-format string

from datetime import datetime

def get_timespec(dt):
    specs = ['hours', 'minutes', 'seconds', 'milliseconds', 'microseconds']
    for timespec in specs:
        if datetime.fromisoformat(dt).isoformat(timespec=timespec) == dt:
            return timespec

sample = ["2018-07-13T00 00:00", # hours
          "2018-07-13T00:00 00:00", # minutes
          "2018-07-13T00:00:00 00:00", # seconds
          "2018-07-13T00:00:00.000 00:00", # milliseconds
          "2018-07-13T00:00:00.000000 00:00"] # microseconds

for dt in sample:
    print(get_timespec(dt))

output

hours
minutes
seconds
milliseconds
microseconds
  • Related