我试图找到昨天和今天之间的区别。如果是昨天,则执行。这是我的代码:
d1 = datetime.datetime.strptime(str(date_posted), "%Y-%m-%d %H:%M:%S")
d2 = datetime.datetime.strptime(str(datetime.datetime.today()), "%Y-%m-%d %H:%M:%S")
difference = abs((d2 - d1).days)
但是我一直收到此错误:
Traceback (most recent call last):
File "C:\Users\fatima.arshad\AppData\Local\Continuum\anaconda2\envs\web_scraping\lib\site-packages\twisted\internet\defer.py", line 654, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "C:/Users/fatima.arshad/PycharmProjects/arabam/DailyArabamSpider.py", line 44, in parse
d2 = datetime.datetime.strptime(str(datetime.datetime.today()), "%Y-%m-%d %H:%M:%S")
File "C:\Users\fatima.arshad\AppData\Local\Continuum\anaconda2\envs\web_scraping\lib\_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "C:\Users\fatima.arshad\AppData\Local\Continuum\anaconda2\envs\web_scraping\lib\_strptime.py", line 365, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: .722653
答案 0 :(得分:0)
如果您只是想获得天数差异,则无需将日期强制转换为字符串,然后返回日期。
private fun createBitmapOverlay(emptyMarkerBitmap: Bitmap, categoryIconBitmap: Bitmap): Bitmap {
val cs: Bitmap
val width: Int = emptyMarkerBitmap.width
val height: Int = emptyMarkerBitmap.height
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val comboImage = Canvas(cs)
comboImage.drawBitmap(emptyMarkerBitmap, 0f, 0f, null)
comboImage.drawBitmap(categoryIconBitmap, emptyMarkerBitmap.width.toFloat(), 0f, null)
return cs
}
如果要剥离微秒,请使用d1 = datetime.datetime.strptime(str(date_posted), "%Y-%m-%d %H:%M:%S")
d2 = datetime.datetime.today()
difference = abs((d2 - d1).days)
.replace()
也就是说,使用d = datetime.today()
print(d) # 2020-04-23 18:09:34.039505
print(d.replace(microsecond=0)) # 2020-04-23 18:09:34
确定两个日期是否至少相隔24小时。如果您想知道昨天是否发生过此事(例如今天的星期四,其他日期是前一个星期三或更早的日期),请按照用户@Daweo的建议使用其日期进行比较。为了完整起见,以下内容包括在内:
timedelta.days == 1
答案 1 :(得分:0)
在按天计算时,您可以将d1
转换为datetime.date
,然后将其与今天的datetime.date
进行比较,即:
import datetime
d1 = datetime.datetime.strptime(str(date_posted), "%Y-%m-%d %H:%M:%S").date()
d2 = datetime.date.today()
difference = abs((d2 - d1).days)