简体   繁体   中英

adding 2 1/2 hours to a time object in python

I need to be able to convert time on an time object I recieve from a sql database into python. Here is the current python code I am using without any conversions. I need to add 2 and 1/2 hours to the time.

def getLastReport(self, sql):



    self.connectDB()
    cursor.execute(sql)
    lastReport = cursor.fetchall()

    date = lastReport[0][0].strftime('%Y-%m-%d %H:%M UTC')

    dataset_id = int(lastReport[0][1])

    cursor.close()
    DATABASE.close()
    return date, dataset_id  

Have you looked at the datetime module? http://docs.python.org/library/datetime.html

Convert your SQL time into a datetime, and make a timedelta object of 2.5 hours. Then add the two.

from datetime import datetime

dt = datetime.strptime( date, '%Y-%m-%d %H:%M' )
dt_plus_25 = dt + datetime.timedelta( 0, 2*60*60 + 30*60 )

添加datetime.timedelta(0, 2.5*60*60)

Try this (switch sqlite3 with whatever db interface you are using):

f= lastReport[0][0]
newtime = sqlite3.Time(f.hour + 2, f.minute + 30, f.second, f.microsecond)

I thought that adding datetime.timedelta(0, 2.5*60*60) like Igancio suggests would be the best solution, but I get:

'unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'.

I usually use the 3rd party module, dateutil, for this sort of thing. It makes this sort of time-shifting much easier to do and understand:

http://labix.org/python-dateutil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM