我想知道insertion_date
是否超过30天。这应该检测到当前时间的分钟和秒。 insertion_date
中的值将从API中动态提取。
当前代码仅检测到当天,我需要精确到秒。
import datetime
import dateutil.parser
insertion_date = dateutil.parser.parse('2017-08-30 14:25:30')
right_now_30_days_ago = datetime.datetime.today() - datetime.timedelta(days=30)
print right_now_30_days_ago #2017-08-31 12:18:40.040594
print insertion_date #2017-08-30 14:25:30
if insertion_date > right_now_30_days_ago:
print "The insertion date is older than 30 days"
else:
print "The insertion date is not older than 30 days"
答案 0 :(得分:8)
你需要在类似的路线上做点什么:
from datetime import datetime, timedelta
time_between_insertion = datetime.now() - insertion_date
if time_between_insertion.days>30:
print "The insertion date is older than 30 days"
else:
print "The insertion date is not older than 30 days"
答案 1 :(得分:4)
from datetime import datetime, timedelta
print(datetime.now())
datetime.datetime(2017, 9, 5, 7, 25, 37, 836117)
print(datetime.now() - timedelta(days=30))
datetime.datetime(2017, 8, 6, 7, 25, 51, 723674)
正如你在这里看到的,它精确到几秒钟。
问题出在datetime.today()
。您应该使用datetime.now()
代替datetime.today()
:
time_since_insertion = datetime.now() - insertion_date
if time_since_insertion.days > 30:
print("The insertion date is older than 30 days")
else:
print("The insertion date is not older than 30 days")
希望它有所帮助!
答案 2 :(得分:0)
如果你已经在你的项目中使用 Pandas,你可以使用 Timedelta 的详细字符串解析非常干净地完成它。它还与 datetime 模块很好地集成:
import pandas as pd
import datetime
insertion_date = datetime.datetime(2021, 1, 1) # Your datetime here
current_datetime = datetime.datetime.now()
if current_datetime - insertion_date < pd.Timedelta("30 days"):
print("Inserted less than 30 days ago")
一件好事是,如果需要,您可以轻松地将其修改为包括小时、秒等,例如 ... <= pd.Timedelta("30 days 12 hours 30 minutes")
。这对于 datetime 模块来说不是那么容易。