【问题标题】:datetime error while converting string to datetime in a If statement在 If 语句中将字符串转换为日期时间时出现日期时间错误
【发布时间】:2020-06-15 13:33:58
【问题描述】:

我已经多次阅读过这个问题,但我就是无法摆脱 datetime 属性错误。管理导入 csv 文件并将最新的日期时间分配给“LastImportDate”。打印出日期没有问题,但是当我在 if 语句中添加以比较“LastImportDate”和“Yesterday”时遇到错误。可以告诉我我的脚本出了什么问题吗?提前致谢。

=====

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

LastTankGaugeBook = pd.read_csv('Final_Tank_Gauge_Book.csv')
LastTankGaugeBook = LastTankGaugeBook.set_index(['Date_Time'])
LastTankGaugeBook = LastTankGaugeBook.sort_index()

LastImportDate = LastTankGaugeBook.index.max()
Today = datetime.today()
Yesterday = Today - timedelta(days=1)
print('Last import date: ', LastImportDate)
print('Today date: ', Today)
print('Yesterday date: ', Yesterday)

def date_stamp(date):
    return datetime.datetime.strptime(date,'%Y/%m/%d')

if date_stamp(LastImportDate) >= date_stamp(Yesterday):
    print('No import operation')
else:
    print('Start import operation')

=======

Output:
Last import date:  2019-01-11 23:00:00
Today date:  2020-06-15 06:28:49.492720
Yesterday date:  2020-06-14 06:28:49.492720
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-131b8da9ab87> in <module>
     42     return datetime.datetime.strptime(date,'%Y/%m/%d')
     43
---> 44 if date_stamp(LastImportDate) >= date_stamp(Yesterday):
     45     print('No import operation')
     46 else:

<ipython-input-8-131b8da9ab87> in unix_stamp(date)
     40
     41 def date_stamp(date):
---> 42     return datetime.datetime.strptime(date,'%Y/%m/%d')
     43
     44 if date_stamp(LastImportDate) >= date_stamp(Yesterday):

AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

【问题讨论】:

    标签: python if-statement python-datetime


    【解决方案1】:

    改变这个

    def date_stamp(date):
        return datetime.strptime(date,'%Y/%m/%d')
    

    【讨论】:

    • 嗨,小伙子哦。
    • 您好,感谢您的快速回复。我将其更改为上述但收到错误:ValueError:未转换的数据仍然存在:23:00:00。然后,我修改为“return datetime.strptime(date,'%Y-%m-%d %H:%M:%S')”并且错误:TypeError: strptime() argument 1 must be str, not datetime.datetime 被提示。
    猜你喜欢
    • 2022-01-26
    • 2015-09-17
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2014-09-21
    • 2012-12-30
    相关资源
    最近更新 更多