简体   繁体   中英

How to use day of the week and the day of the month to get year in python?

for example how would you get "2016" from

Fri, Feb, 19 ?

I have a database from somewhere that has entries from the last 4 years but only lists dates as day of the week and day of the month, and I need to get the year from each. There should not be any repetitions because there is only four years of data, and date & day of the week alignments do not repeat in that timeframe.

How about this:

import datetime

year = next(date for year in (2013, 2014, 2015, 2016)
            for date in (datetime.date(year, 2, 19),)
            if date.weekday() == 4).year

这与击败我的@zondo答案略有不同,但是无论如何我都会提出来,因为我不.year在长表达式的结尾使用.year

year = next(y for y in range(2013, 2017) if datetime.date(y, 2, 19).weekday() == 4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM