![](/img/trans.png)
[英]Python 'datetime.timedelta' object has no attribute 'time' error
[英]Error getting Time from datetime.timedelta object in python
我想从datetime.timedelta对象中以“ HH:MM”的格式检索时间。 我有一个表存储在MySQL数据库中。 它具有“时间”列,该列以格式存储时间,
00:00:00
我已经使用PyMySQL模块连接到MySQL服务器,
conn = pymysql.connect("localhost", "root", "cloudera", "streaming")
cursor = conn.cursor()
sql = "select * from table1 limit 5;"
cursor.execute(sql)
row = cursor.fetchone()
row[1]
输出是
datetime.timedelta(0)
我已经看过这篇文章Python:如何从datetime.timedelta对象获取时间? 。 但是与那个问题和我的问题的区别在于输出结果。 对于该帖子,输出为
datetime.timedelta(0, 64800)
对我来说,
datetime.timedelta(0)
我只是不明白为什么我的输出是这种方式。 谁能帮我找回时间。 提前致谢。
当您键入row[1]
python将打印变量的repr-在这种情况下,timedelta的repr是“ datetime.timedetla(days,seconds)”。
您可以使用str
对其进行字符串化处理,但这会给您HH:MM:SS
str(row[1])
-> "23:00:00"
要获取HH:MM,您可以执行以下操作:
(datetime.min + row[1]).strftime("%H:%M")
-> "23:00"
因此,您的代码应如下所示:
conn = pymysql.connect("localhost", "root", "cloudera", "streaming")
cursor = conn.cursor()
sql = "select * from table1 limit 5;"
cursor.execute(sql)
row = cursor.fetchone()
timestr = (datetime.min + row[1]).strftime("%H:%M")
print(timestr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.