1

I have a string lfile with a datetime in it (type(lfile) gives <type 'str'>) and a Python datetime object wfile. Here is the code:

import os, datetime
lfile = '2005-08-22_11:05:45.000000000'
time_w = os.path.getmtime('{}\\{}.py' .format('C:\Temp_Readouts\RtFyar','TempReads.csv'))
wfile = datetime.datetime.fromtimestamp(time_w)

wfile contains this 2006-11-30 19:08:06.531328 and repr(wfile) gives:

datetime.datetime(2006, 11, 30, 19, 8, 6, 531328)

Problem:

I need to:

  1. convert lfile into a Python datetime object
  2. compare lfile to wfile and determine which datetime is more recent

For 1.:

I am only able to get a partial solution using strptime as per here. Here is what I tried:

lfile = datetime.datetime.strptime(linx_file_dtime, '%Y-%m-%d_%H:%M:%S')

The output is:

`ValueError: unconverted data remains: .000`

Question 1

It seems that strptime() cannot handle the nano seconds. How do I tell strptime() to ignore the last 3 zeros?

For 2.:

When I use type(wfile) I get <type 'datetime.datetime'>. If both wfile and lfile are Python datetime objects (i.e. if step 1. is successful), then would this work?:

if wtime < ltime:
    print 'Linux file created after Windows file'
else:
    print 'Windows file created after Linux file'

Question 2

Or is there some other way in which Python can compare datetime objects to determine which of the two occurred after the other?

Community
  • 1
  • 1
edesz
  • 11,756
  • 22
  • 75
  • 123

2 Answers2

2

Question 1

Python handles microseconds, not nano seconds. You can strip the last three characters of the time to convert it to microseconds and then add .%f to the end:

lfile = datetime.datetime.strptime(linx_file_dtime[:-3], '%Y-%m-%d_%H:%M:%S.%f')

Question 2

Yes, comparison works:

if wtime < ltime:
    ...
Alexander
  • 105,104
  • 32
  • 201
  • 196
1

That's right, strptime() does not handle nanoseconds. The accepted answer in the question that you linked to offers an option: strip off the last 3 digits and then parse with .%f appended to the format string.

Another option is to use dateutil.parser.parse():

>>> from dateutil.parser import parse
>>> parse('2005-08-22_11:05:45.123456789', fuzzy=True)
datetime.datetime(2005, 8, 22, 11, 5, 45, 123456)

fuzzy=True is required to overlook the unsupported underscore between date and time components. Because datetime objects do not support nanoseconds, the last 3 digits vanish, leaving microsecond accuracy.

mhawke
  • 84,695
  • 9
  • 117
  • 138
  • Ha! Apologies for missing that. Seems the question might already have been answered in that earlier link I posted. Thanks for your answer as well! – edesz Jul 29 '16 at 19:57