简体   繁体   English

Python:我怎样才能看出今年某个月和今天是否已经过去了?

[英]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.

相关问题 给定日期列表,我如何将它们组合/格式化为字符串,例如“Day1-Day3,Day5 Month Year” - Given a list of dates, how can I combine/format them as a string like "Day1-Day3, Day5 Month Year" Python中如何将日/月/年格式改为月/日/年 - How to change Day/Month/Year format to Month/Day/Year in Python 如何将日期从日-月-年重新格式化为年-月-日? - How can I reformat date from day-month-year to year-month-day? 如何从Python日期时间获得时区感知的年,月,日,小时等? - How can I get the timezone-aware year, month, day, hour etc. from a Python datetime? 如何从 Python 中的 Deephaven DateTime 获取年、月和日? - How can I get the year, month, and day from a Deephaven DateTime in Python? python - 如何找到用户给定的一个月的第一天,用户给定的一年中的哪一天落在python中 - how to find on which day the first of a month, given by user, in a year, given by user, falls in python 如何将此日期格式化为日 - 月 - 年 - How can I format this date into Day - Month - Year 在 python 中查找给定日期(年、月、日)时需要帮助 - Need help in finding the day of given (year,month,date) in python 在 Python 中将年/月/日转换为年中的第几天 - Convert Year/Month/Day to Day of Year in Python 如果给定的日期是本月的最后一天,如何增加月份数? - How can I increment month number if given day is last day of current month?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM