python - compare the date in the string with today's date

て烟熏妆下的殇ゞ 提交于 2021-02-08 02:56:09

问题


objective:

  • compare the date in the string with today's date

Issue:

  • get this error:ValueError: unconverted data remains: 12:00:00

question:

  • how do a fix that error
  • how do i remove the time element of the string?

Code

from datetime import date
from datetime import time
from datetime import datetime

dateTimeStart = "2014-01-01 12:00:00"

def main():
    dateTime1 = datetime.strptime(dateTimeStart, "%Y-%m-%d")
    today = date.today()

    if dateTime1 > "today":
        print "No"

if __name__ == "__main__":
  main();

回答1:


You need to parse the time part as well:

datetime.strptime(dateTimeStart, "%Y-%m-%d %H:%M:%S")

Then you can compare your dates like this:

if dateTime1.date() > date.today():
    print "No"

The date() function returns the date of a datetime object.



来源:https://stackoverflow.com/questions/32287708/python-compare-the-date-in-the-string-with-todays-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!