在Python中向时间对象添加2小时30分钟
我需要把从SQL数据库里得到的时间对象转换成Python中的时间。下面是我现在使用的Python代码,没有进行任何转换。我需要在这个时间上加上2个半小时。
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
4 个回答
1
试试这个(把sqlite3换成你正在使用的数据库接口):
f= lastReport[0][0]
newtime = sqlite3.Time(f.hour + 2, f.minute + 30, f.second, f.microsecond)
我原以为像Igancio建议的那样加上datetime.timedelta(0, 2.5*60*60)会是最好的解决办法,但我得到了:
'unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'.
1
添加 datetime.timedelta(0, 2.5*60*60)
。
3
你有没有看过datetime模块? http://docs.python.org/library/datetime.html
把你的SQL时间转换成datetime格式,然后创建一个2.5小时的时间差对象。接着把这两个加起来。
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 )