pythondatetimedatetime-comparison

how to convert string 'Jan 23 2016 10:30:08AM' or string '23/01/2016 10:30:08' to epoch time in python?


I want to compare 2 times including dates. for example : 'Jan 23 2016 4:16:09PM' and 'Jan 24 2016 9:43:44PM'

i think the easiest and best way is to convert it in epoch and compare. (Please let me know if there is any other approach better than this)

i tried this :

from dateutil.parser import parse
import datetime

timer = 'Jan 23 2016 10:30:08AM'
d = parse(timer).strftime('%Y,%m,%d,%H,%M,%S')

>>> d
'2016,01,23,10,30,08'

but it as it is a string, i am not able to pass this value datetime.datetime(d) i tried to strip() as well. but din't work.

datetime.datetime(d.strip())

TypeError: an integer is required (got type str)

Please help.


Solution

    1. Parse already returns datetime object. .strftime converts datetime object to a string, hence it doesn't work.

    2. datetime objects are already comparable, you don't have to convert them to epoch:

    >>> from dateutil.parser import parse
    >>> d1 = parse("Jan 23 2016 4:16:09PM")
    >>> d2 = parse("Jan 24 2016 9:43:44PM")
    >>> d1
    datetime.datetime(2016, 1, 23, 16, 16, 9)
    >>> d2
    datetime.datetime(2016, 1, 24, 21, 43, 44)
    >>> d1 > d2
    False
    >>> d1 == d2
    False
    >>> d1 < d2
    True