Read time and date from a text file

Peter Otten __peter__ at web.de
Wed Nov 24 08:09:31 EST 2010


huisky wrote:

> As a newbie, I posted my question here again.
> say i have two dics read from a text file by 'split'.

Please don't start a new thread when you are still asking about the same 
topic.

>>>> 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']})

I think you should use a normal dict. A default value of 0 doesn't make much 
sense here.
 
> 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.

Chris Rebert also suggested that you use the strptime() method. To spell it 
out a bit:

>>> s = " ".join(cstart[18291])
>>> s
'Dec 6 21:01:17'
>>> datetime.datetime.strptime(s, "%b %d %H:%M:%S")
datetime.datetime(1900, 12, 6, 21, 1, 17)

You can learn about the format codes here:

http://docs.python.org/library/time.html#time.strftime

Note that strptime() assumes 1900 as the year which may lead to errors in 
leapyears and when start and completion time are in different years.

Peter



More information about the Python-list mailing list