Python:我如何从datetime.timedelta对象中获取时间?
A mysql database table has a column whose datatype is time ( http://dev.mysql.com/doc/refman/5.0/en/time.html ). When the table data is accessed, Python returns the value of this column as a datetime.timedelta object. How do I extract the time out of this? (I didn't really understand what timedelta is for from the python manuals).
mysql数据库表有一个数据类型为time的列(http://dev.mysql.com/doc/refman/5.0/en/time.html)。访问表数据时,Python将此列的值作为datetime.timedelta对象返回。如何从中抽出时间? (我真的不明白timedelta是从python手册中得到的)。
E.g. The column in the table contains the value "18:00:00" Python-MySQLdb returns this as datetime.timedelta(0, 64800)
例如。表中的列包含值“18:00:00”Python-MySQLdb将其返回为datetime.timedelta(0,64800)
Please ignore what is below (it does return different value) -
请忽略下面的内容(它会返回不同的值) -
Added: Irrespective of the time value in the table, python-MySQLdb seems to only return datetime.timedelta(0, 64800).
补充:无论表中的时间值如何,python-MySQLdb似乎只返回datetime.timedelta(0,64800)。
Note: I use Python 2.4
注意:我使用Python 2.4
2 个解决方案
#1
31
It's strange that Python returns the value as a datetime.timedelta
. It probably should return a datetime.time
. Anyway, it looks like it's returning the elapsed time since midnight (assuming the column in the table is 6:00 PM). In order to convert to a datetime.time
, you can do the following::
奇怪的是,Python将值返回为datetime.timedelta。它可能应该返回datetime.time。无论如何,看起来它正在返回自午夜起的经过时间(假设表中的列是下午6:00)。要转换为datetime.time,您可以执行以下操作::
value = datetime.timedelta(0, 64800)
(datetime.datetime.min + value).time()
datetime.datetime.min
and datetime.time()
are, of course, documented as part of the datetime module if you want more information.
当然,如果您需要更多信息,datetime.datetime.min和datetime.time()会记录为datetime模块的一部分。
A datetime.timedelta
is, by the way, a representation of the difference between two datetime.datetime
values. So if you subtract one datetime.datetime
from another, you will get a datetime.timedelta
. And if you add a datetime.datetime
with a datetime.timedelta
, you'll get a datetime.datetime
. That's how the code above works.
顺便提一下,datetime.timedelta是两个datetime.datetime值之间差异的表示。因此,如果从另一个中减去一个datetime.datetime,您将获得datetime.timedelta。如果您使用datetime.timedelta添加datetime.datetime,您将获得datetime.datetime。这就是上面代码的工作原理。
更多相关文章
- mysql 排序两个字段/列表先根据时间升序排序,时间相同再根据商家I
- 数据类型和运算符 MySQL学习笔记
- 在H2数据库中插入时间——函数“PARSEDATETIME”未找到
- Java MySQL数据类型对照
- MySQL数据类型中DECIMAL的作用和用法
- MySQL在保存数据时添加时间戳
- mysql查询一条工单时间需要10秒。优化sql语句得以解决。
- 如何使用PDO从MySQL获取正确的数据类型?
- 如何从mysql datetime列返回转换后的时间格式?