简体   繁体   English

比较两个日期时间的类型错误

[英]Type error comparing two datetimes

My problem will look common to you, but I didn't find the answer on the website. 我的问题对您来说很常见,但是我没有在网站上找到答案。 I want to combine two dates in python, I use this : 我想在python中合并两个日期,我用这个:

delta = 2012-04-07 18:54:40  - 2012-04-07 18:54:39

But I get an error : TypeError: unsupported operand type(s) for -: 'str' and 'str' 但我收到一个错误: TypeError: unsupported operand type(s) for -: 'str' and 'str'

I understand it, but I don't know how to turn it the right way. 我理解它,但是我不知道如何正确地将它变成正确。

Do you have an idea? 你有想法吗?

Thks! THKS!

You are subtracting strings , not datetime.datetime objects. 您要减去strings ,而不是datetime.datetime对象。 Try the strptime method in order to convert from strings to datetime.datetime . 尝试使用strptime方法从字符串转换为datetime.datetime

>>> delta = datetime.datetime.strptime('2012-04-07 18:54:40', '%Y-%m-%d %H:%M:%S') \
            - datetime.datetime.strptime('2012-04-07 18:54:39', '%Y-%m-%d %H:%M:%S')
>>> delta
datetime.timedelta(0, 1)

Make them datetimes! 使它们成为日期时间!

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2013, 5, 13, 10, 25, 6, 20914)
>>> datetime.datetime(2013, 5, 13, 10, 25, 6, 20914)
datetime.datetime(2013, 5, 13, 10, 25, 6, 20914)
>>> datetime.datetime(2013, 5, 13, 10, 25, 6, 20914) - datetime.datetime(2013, 5, 13, 10, 14, 6, 20914)
datetime.timedelta(0, 660)
>>> 

If you want to calculate with datetimes, you first have to parse the date strings you've got. 如果要使用日期时间进行计算,则首先必须解析您拥有的日期字符串。

One possibility is strptime, as mentioned. 如上所述,一种可能性是strptime。 You can also use python-dateutil : 您还可以使用python-dateutil

import dateutil.parser
dateutil.parser.parse("2012-04-07 18:54:40") - dateutil.parser.parse("2012-04-07 18:54:39")

# datetime.timedelta(0, 1)

which is easier to use. 这更容易使用。 Also, there are a lot of other useful things for date handling in dateutil. 另外,dateutil中还有许多其他有用的东西可用于日期处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM