[英]Python: How can I see if a given month and day have already passed this year?
Today it's 16 Feb
. 今天是
16 Feb
。 I have a string 23 Mar
. 我有一个字符串
23 Mar
How can I check if my string is before or after the current day? 如何检查我的字符串是在当天之前还是之后?
I have a list of files with the last modified date attached. 我有一个附有最后修改日期的文件列表。 They only have a day and month, no year.
他们只有一天一个月,没有一年。 If the date has already passed this year (eg 16/01), the year should be 2014, if not (eg 30/12), the year should be 2013.
如果该日期已经过去了今年(例如16/01),则该年份应为2014年,如果不是(例如30/12),则该年份应为2013年。
Parse out the string into a datetime
object using datetime.datetime.strptime()
, but since your date string has no year attached to it, do attach the current year to it: 使用
datetime.datetime.strptime()
将字符串解析为datetime
对象,但由于您的日期字符串没有附加年份,请将当前年份附加到它:
import datetime
today = datetime.date.today()
yourdate = datetime.datetime.strptime(inputstring, '%d %b')
yourdate = yourdate.date().replace(year=today.year)
if yourdate >= today:
# date not before today, attach *last* year
yourdate = yourdate.replace(year=today.year - 1)
I converted the datetime
object to a date
object here too since we only need to talk about dates. 我转换的
datetime
对象的date
对象也在这里,因为我们只需要谈的日期。
This does assume your date strings always are of the form day-of-the-month month-abbreviated in English. 这假设您的日期字符串始终是以英语缩写的月份日期形式。
Demo: 演示:
>>> import datetime
>>> inputstring = '23 Mar'
>>> today = datetime.date.today()
>>> yourdate = datetime.datetime.strptime(inputstring, '%d %b')
>>> yourdate = yourdate.date().replace(year=today.year)
>>> yourdate
datetime.date(2014, 3, 23)
>>> yourdate >= today
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.