user392409
user392409

Reputation: 143

Comparing dates and times in different formats using Python

I have lines of the following format in a file.

Summary;meeting;Description;None;DateStart;20100629T110000;DateEnd;20100629T120000;Time;20100805T084547Z

I need to create a function that has two inputs: time and date in the following formats Time: HH:MM and date as mmddyyyy. (These are strings). Now the function needs to read this line and see if the the input date and time, lies between DateStart(20100629T11000) and DateEnd(20100629T120000). How do i deal with this since the format of date and time in the input and the line are in two formats?

Upvotes: 2

Views: 9121

Answers (3)

chryss
chryss

Reputation: 7519

Use the datetime class inside the datetime module. Here is a function that does what you need, though you might need to adjust boundary conditions:

from datetime import datetime
def f(row, datestr, timestr):
    tmp = row.split(";")
    start = datetime.strptime(tmp[5], "%Y%m%dT%H%M%S")
    end = datetime.strptime(tmp[7], "%Y%m%dT%H%M%S")
    mytimestamp = datetime.strptime(datestr+timestr, "%d%m%Y%H:%M")
    if (start < mytimestamp and mytimestamp < end):
        print "inside"
    else:
        print "not inside"

>>> f("Summary;meeting;Description;None;DateStart;20100629T110000;DateEnd;20100629T120000;Time;20100805T084547Z", "29062010", "11:00")
not inside
>>> f("Summary;meeting;Description;None;DateStart;20100629T110000;DateEnd;20100629T120000;Time;20100805T084547Z", "29062010", "11:30")
inside

Upvotes: 1

Katriel
Katriel

Reputation: 123712

To handle dates and times, use Python's datetime module. The datetime class in that module has a method for reading datetimes from strings, called strptime. So you can do:

# read the file, so that:
strStart = "20100629T110000"
strEnd = "20100629T120000"
imTime = "HH:MM"
inDate = "mmddyyyy"

import datetime
dateStart = datetime.datetime.strptime( strStart, "%Y%m%dT%H%M%S" )
dateEnd = datetime.datetime.strptime( strEnd, "%Y%m%dT%H%M%S" )
dateIn = datetime.datetime.strptime( inDate + inTime, "%m%d%Y%H:%M" )

assert dateStart < dateIn < dateEnd

N.B. You can use csv to read the file.

Upvotes: 1

kennytm
kennytm

Reputation: 523464

You can parse a string into a datetime with strptime:

>>> datetime.datetime.strptime('20100629T110000', '%Y%m%dT%H%M%S')
datetime.datetime(2010, 6, 29, 11, 0)
>>> datetime.datetime.strptime('23:45 06192005', '%H:%M %m%d%Y')
datetime.datetime(2005, 6, 19, 23, 45)

And then you can compare (<, <=, etc) the two datetimes.

Upvotes: 4

Related Questions