Search code examples
pythonpython-2.7datetimestrptime

Python convert string to datetime for comparison to datetime object


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?


Solution

  • 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:
        ...