tags:

views:

52

answers:

3

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?

+2  A: 

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.

KennyTM
+1 Beat me to it!
katrielalex
Hello Kenny, what version of Python are you using. I am using 2.4, and i have imported all required, but i am getting error while using datetime.datetime.strptime.
@user: `datetime.strptime` is available since 2.5 as shown in the link. You could use `time.strptime` but the API is less object-oriented. Why not upgrade to Python 2.7?
KennyTM
Thanks vey much, just installed 2.7, and made my life so much easier!
+1  A: 

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.

katrielalex
+1  A: 

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
chryss