[Tutor] Getting Date/Time from a file and using it in calculations

Martin Walsh mwalsh at groktech.org
Thu Aug 16 05:12:17 CEST 2007


dgj502 at york.ac.uk wrote:
> Hello there
> 
> Messing around with certain time and datetime objects, I have managed to 
> subtract a date/time from the present time thusly:
> 
> from time import *
> import datetime
> 
> one = datetime.datetime.now()
> two  = datetime.datetime(2007, 8, 29, 11, 15, 00)
> 
> difference = one - two
> 
> print difference
> 
> However, I have to take a date from a file and then insert it to where two 
> should be, however to no success. I have managed to get a string containing 
> the above date/time, but that is as far as I've gotten without it not 
> working.
> 
> Does anyone have any ideas on how to do this properly?  
> 
> Also I wish to display the result only in seconds left, rather than the 
> current result, which just displays days/hours/minutes/seconds/milliseconds 
> left, but am again struggling to progress.

Have a look at time.strptime (and time.mktime) -- you may be able to
drop datetime entirely. Here is my attempt (not tested):

import time

time_string = '2007/08/15 22:10:21'
one = time.time() # now
two = time.mktime(time.strptime(time_string, '%Y/%m/%d %H:%M:%S'))

# difference in seconds (float)
difference = one - two

HTH,
Marty



More information about the Tutor mailing list