如何从 datetime.timedelta 对象获取时间?
mysql 数据库表有一列,其数据类型为时间 ( http://dev .mysql.com/doc/refman/5.0/en/time.html)。 当访问表数据时,Python 会以 datetime.timedelta 对象的形式返回该列的值。 我如何从中提取时间? (我从Python手册中并没有真正理解timedelta的用途)。
例如,表中的列包含值“18:00:00” Python-MySQLdb 将其返回为 datetime.timedelta(0, 64800)
请忽略下面的内容(它确实返回不同的值) -
添加:无论表中的时间值如何,python-MySQLdb 似乎只返回日期时间。 timedelta(0, 64800).
注意:我使用 Python 2.4
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).
E.g. The column in the table contains the value "18:00:00"
Python-MySQLdb returns this as 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).
Note: I use Python 2.4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
奇怪的是,Python 以
datetime.timedelta
形式返回值。 它可能应该返回一个datetime.time
。 不管怎样,它看起来像是返回自午夜以来经过的时间(假设表中的列是下午 6:00)。 为了转换为datetime.time
,您可以执行以下操作::datetime.datetime.min
和datetime.time()
是当然,如果您想了解更多信息,请记录为 datetime 模块的一部分。顺便说一句,
datetime.timedelta
是两个datetime.datetime
值之间差异的表示。 因此,如果您从一个datetime.datetime
中减去另一个datetime.timedelta
,您将得到一个datetime.timedelta
。 如果您将datetime.datetime
与datetime.timedelta
添加,您将获得datetime.datetime
。 这就是上面的代码的工作原理。It's strange that Python returns the value as a
datetime.timedelta
. It probably should return adatetime.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 adatetime.time
, you can do the following::datetime.datetime.min
anddatetime.time()
are, of course, documented as part of the datetime module if you want more information.A
datetime.timedelta
is, by the way, a representation of the difference between twodatetime.datetime
values. So if you subtract onedatetime.datetime
from another, you will get adatetime.timedelta
. And if you add adatetime.datetime
with adatetime.timedelta
, you'll get adatetime.datetime
. That's how the code above works.在我看来,MySQL 中的 TIME 类型旨在表示时间间隔,就像 Python 中的 datetime.timedelta 一样。 从您引用的文档中:
从 datetime.timedelta 转换为 datetime.time 的替代方法是将列类型更改为 DATETIME 并且不使用日期字段。
-插入:
-选择:
在日期时间对象上调用 datetime.time() 以获取时间对象。
It seems to me that the TIME type in MySQL is intended to represent time intervals as datetime.timedelta does in Python. From the docs you referenced:
An alternative to converting from datetime.timedelta to datetime.time would be to change the column type to DATETIME and not using the date fields.
-Insert:
-Select:
datetime.time() is called on a datetime object to get a time object.