简体   繁体   中英

Extract month, date, and year from MMDDYYYY when given as a input in that format. Using only math

I cannot figure out how to get DD and YYYY separated. For MM I did:

MMDDYYYY = int(input("enter" ))
month = MMDDYYYY // 1000000

Tried using % but could not figure out where to place it.

Using integer division ( divmod ) which returns quotient and remainder in one operation:

MMDDYYYY  = int(input("enter" ))
MMDD,YYYY = divmod(MMDDYYYY,10000) # extract the year
MM,DD     = divmod(MMDD,100)       # extract month and day

Or using divisions and modulo. Division ( // ) by 10 eliminates the last digit. Division by 100 eliminates the last 2 digits, and so on. So you can strip the 4 digits of the year using a division by 10000 and you can eliminate the 6 digits of the day and year (to get the month) by dividing by 1000000. A modulo of 100 extracts the last two digits (eg to get the day out of MMDDYYY//10000). A module 10000 extracts the last 4 digits (eg the year)

MMDDYYYY  = int(input("enter" ))
YYYY      = MMDDYYYY %  10000       
DD        = MMDDYYYY // 10000 % 100
MM        = MMDDYYYY // 1000000

Use the modulus operator in conjunction with division (try online)

month = MMDDYYYY // 1000000
day = MMDDYYYY % 1000000 // 10000
year = MMDDYYYY % 10000
print(month, day, year)

Try it with datetime .

import datetime
MMDDYYYY = int(input("enter" ))
date = datetime.datetime.strptime(str(MMDDYYYY), "%m%d%Y")

You can simply get year , month , date as following:

date.month
date.year
date.day

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