2009/3/30 pa yo <payo2...@gmail.com>: > I need to add one minute to a string that has a date and a time in > YYYYMMDDHHMM format. > e.g: 200903281346 should become 200903281347 > > the following script converts the string into time and adds one > minute; but somehow I also add an hour and I don't understand why. > > ==================== > > import time > > #set the initial time as a string and convert it into time format: > fromtimestring = '200903281346' > fromtimetime = time.strptime(fromtimestring, "%Y%m%d%H%M") > #convert this time format into UNIX time (seconds since the start of UNIX > time): > fromtimeseconds = time.mktime(fromtimetime) > #add 60 seconds and reformat the result into the YYYYMMDDHHMM format > totimeseconds = fromtimeseconds + 60 > totimetime = time.gmtime(totimeseconds) > # convert the new time into a string: > totimestring = time.strftime("%Y%m%d%H%M", totimetime) > > #print the results: > print (fromtimestring) > print (fromtimetime) > print (totimetime) > print (totimestring) > > ================ > > any help or suggestions would be much appreciated.
You could do this with datetime and timedelta from the datetime module. >>> from datetime import datetime, timedelta >>> fromtimetime = datetime.strptime('200903281346', '%Y%m%d%H%M') >>> fromtimetime datetime.datetime(2009, 3, 28, 13, 46) >>> delta = timedelta(seconds=60) >>> delta datetime.timedelta(0, 60) >>> fromtimetime + delta datetime.datetime(2009, 3, 28, 13, 47) >>> datetime.strftime(fromtimetime + delta, '%Y%m%d%H%M') '200903281347' Greets Sander _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor