比较Python中的两个日期字符串 [英] Comparing two date strings in Python

查看:262
本文介绍了比较Python中的两个日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串: 10/12/13和 10/15/13,如何将它们转换为日期对象,以便比较日期?例如,查看哪个日期之前或之后。

Let's say I have a string: "10/12/13" and "10/15/13", how can I convert them into date objects so that I can compare the dates? For example to see which date is before or after.

推荐答案

使用 datetime.datetime.strptime

>>> from datetime import datetime as dt
>>> a = dt.strptime("10/12/13", "%m/%d/%y")
>>> b = dt.strptime("10/15/13", "%m/%d/%y")
>>> a > b
False
>>> a < b
True
>>>

这篇关于比较Python中的两个日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆