【问题标题】:Compare two datetime stringspython比较两个日期时间字符串python
【发布时间】:2019-03-29 14:14:25
【问题描述】:

我需要比较下面给出的两个日期:

my_date = 'Mar 15 00:00:00 2019'
date_to_check = "Sep 17 04:00:05 2018"

if my_date<=date_to_check:
     print(True)

它不应该打印任何东西。但它正在打印“True”。我发现了问题——它只比较了 3 月 15 日到 9 月 17 日,没有考虑到年份。 而且我无法将日期格式更改为其他格式,因为我需要比较文本文件中的日期。

任何关于此的cmets。

【问题讨论】:

标签: python-3.x datetime


【解决方案1】:
from datetime import datetime

my_date = 'Mar 15 00:00:00 2019'
date_to_check = "Sep 17 04:00:05 2018"

my_date_object = datetime.strptime(my_date, '%b %d %H:%M:%S %Y')
date_to_check_object = datetime.strptime(date_to_check, '%b %d %H:%M:%S %Y')

if my_date_object <= date_to_check_object:
    print(True)

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 2013-12-20
    • 1970-01-01
    • 2020-06-10
    • 2013-09-14
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多