Python exercise 004: Determine if a date is the day ordinal of the year

Source: Internet
Author: User

"python exercise 004" Enter a certain day of the year, judging the day is the first of the year?

----------------------------------------------

This problem actually wrote 28 lines of code! It also does not include validation of the input data (only assuming that the date entered is strictly in the format). But I firmly believe that there must be a more concise approach, such as Python's handling of dates.

However, they have not learned this knowledge, now can only be solved with a silly big way. When you learn advanced ways to update it ~ ~ ~

Idea: First to determine whether it is a leap year, which concerns the number of days in February. Then, according to the month value to add up the number of days before the first few months, and finally add a "day", it is OK.

1DAT = input ('Please enter a certain day of the year, the format is YYYY-MM-DD:')2y = Int (dat[0:4])#Get year3m = Int (Dat[5:7])#Get Month4d = Int (dat[8:])#Get Day5 6ly =False7 8 ify%100 = = 0:#If the year can be divisible by 1009     ify%400 = = 0:#and can be divisible by 400 .Tenly = True#is a leap year One     Else: Aly =False - elifY%4 = = 0:#in other cases, if you can divide by 4 -ly = True#is a leap year the Else: -ly =False -  - ifly = = True:#if it is a leap year, there are 29 days in February +ms = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] - Else: +ms = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] A  atDays =0 -  forIinchRange (1, 13):#Judging from 1 to 12 to determine the month -     ifi = =m: -          forJinchRange (i-1):#after the month I is determined, the first i-1 items in the MS list are added -Days + =Ms[j] -         Print('%s is the%s day of the year. '% (DAT, (days + D)))#finally Add "Day", that is the answer

Ask the great God to help simplify this slag code. Kneel, thank you!

Python exercise 004: Determine if a date is the day ordinal of the year

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.