Read time and date from a text file

Tim Williams tjandacw at cox.net
Wed Nov 24 08:05:23 EST 2010


On Nov 24, 7:45 am, huisky <hui... at gmail.com> wrote:
> Hi,
>
> As a newbie, I posted my question here again.
> say i have two dics read from a text file by 'split'.
>
> >>> cstart
>
> defaultdict(<type 'int'>, {15424: ['Dec', '6', '18:57:40'], 552:
> ['Dec', '7', '09:31:00'], 15500: ['Dec', '6', '20:17:02'], 18863:
> ['Dec', '7', '13:14:47'], 18291: ['Dec', '6', '21:01:17'], 18969:
> ['Dec', '7', '14:28:42'], 18937: ['Dec', '7', '14:21:34']})
>
> >>> ccompl
>
> defaultdict(<type 'int'>, {15424: ['Dec', '6', '19:42:55'], 18291:
> ['Dec', '6', '21:01:28'], 15500: ['Dec', '6', '20:26:03'], 18863:
> ['Dec', '7', '13:24:07']})
>
> and I need to calculate the difference time if the key value is the
> same in both dics.
>
> Someone suggested me to use the module 'datetime', but I'm still
> wondering how to make it work.
> I mean how to assign ['Dec','6','21:01:17'] to a 'datetime' object and
> then do the datetime operation.
>
> >>>time=datetime.datetime(cstart[18291])       does NOT work.
>
> thanks in advance
> Huisky

You can use datetime.datetime.strptime() to create a datetime object
from a string representing a date


>>> import datetime
>>> datetime.datetime.strptime('Dec 7  13:24:07','%b %d %H:%M:%S')
datetime.datetime(1900, 12, 7, 13, 24, 7)

Of course, you need to put in the correct year.

datetime.strptime(date_string, format)
Return a datetime corresponding to date_string, parsed according to
format. This is equivalent to datetime(*(time.strptime(date_string,
format)[0:6])). ValueError is raised if the date_string and format
can’t be parsed by time.strptime() or if it returns a value which
isn’t a time tuple.




More information about the Python-list mailing list