本文介绍了Python:如何从datetime.timedelta对象获取时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mysql数据库表中有一列,其数据类型为时间( http: //dev.mysql.com/doc/refman/5.0/en/time.html ).当访问表数据时,Python返回此列的值作为datetime.timedelta对象.如何从中提取时间? (从python手册中我不太了解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).

例如表中的列包含值"18:00:00"Python-MySQLdb将其返回为datetime.timedelta(0,64800)

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) -

已添加:与表中的时间值无关,python-MySQLdb似乎仅返回datetime.timedelta(0,64800).

注意:我使用的是Python 2.4

Note: I use Python 2.4

推荐答案

奇怪的是,Python将值返回为datetime.timedelta.它可能应该返回datetime.time.无论如何,看起来它正在返回自午夜以来的经过时间(假设表中的列为6:00 PM).为了转换为datetime.time,您可以执行以下操作:

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::

value = datetime.timedelta(0, 64800)
(datetime.datetime.min + value).time()

当然,

datetime.datetime.mindatetime.time() datetime datetime 模块,如果您需要更多信息.

datetime.datetime.min and datetime.time() are, of course, documented as part of the datetime module if you want more information.

A datetime.timedelta是两个datetime.datetime值之间差异的表示.因此,如果您从另一个减去一个datetime.datetime,您将得到一个datetime.timedelta.并且,如果将datetime.datetimedatetime.timedelta相加,则会得到datetime.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.

这篇关于Python:如何从datetime.timedelta对象获取时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:31
查看更多