1

I'm writing the time to an XML file and later coming back to compare it against the current time. I've not done this with Python before and the time formatting seems to be pretty strange.

I've managed to put something together if I write the timenow to the XML without milliseconds.

IF the XML has a timestamp like 2016-01-05 00:39:20 then this works:

tree = ET.parse('C:\logs\XMLFILENAME.xml')
    for matchlisting in tree.findall('Found'):
        age = matchlisting.find('FoundTime').text
    dnow=datetime.datetime.now()
    print dnow

    d2 = datetime.datetime.strptime(age, '%Y-%m-%d %H:%M:%S')

    #print d2
    print(dnow-d2)

But by default the time.now doesn't give something like 2016-01-05 00:39:20 it adds the milliseconds on the back like 2016-01-05 00:39:20.xxxx.

I don't see an option for the milliseconds in the documentation to handle it with the strptime or a way to write the timenow without the milliseconds which would work as well.

I'm hoping there's some simple syntax to fix one of these. I'd appreciatea pointer here it's been a few hours on what should be fairly straight forward I would of thought.

PoweredByCoffee
  • 1,153
  • 3
  • 14
  • 25
  • To write the time now without the microseconds without having to use a format string and keeping the processing inside `datetime` use the `replace` method: `datetime.datetime.now().replace(microsecond=0)`. See these questions: https://stackoverflow.com/questions/3183707/stripping-off-the-seconds-in-datetime-python and https://stackoverflow.com/questions/5476065/how-to-truncate-the-time-on-a-datetime-object – NeilG Sep 01 '23 at 04:42

1 Answers1

5

The default conversion to str for display of a datetime object includes microseconds. If you don't want to see it, specify a custom format with strftime:

>>> from datetime import datetime
>>> d = datetime.now()
>>> d
datetime.datetime(2016, 1, 4, 17, 31, 32, 976902)
>>> print(d)
2016-01-04 17:31:32.976902
>>> print(d.strftime('%Y-%m-%d %H:%M:%S'))
2016-01-04 17:31:32

datetime objects also support custom formatting for format:

>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2016-01-04 17:31:32'

Also, the formatting character for the microseconds is %f:

>>> print(d.strftime('%Y-%m-%d %H:%M:%S.%f'))
2016-01-04 17:31:32.976902

Ref: strftime() and strptime() Behavior

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251