0

Please explain the second line in below code

Please explain the second line in below code s = time.strftime("%Y_%m_%d") theday = datetime.date(*map(int, s.split('_'))) previous_day = theday - datetime.timedelta(days=1)

22nd Mar 2019, 11:39 AM
Raj Charan
3 ответов
+ 4
hi Raj, the line: theday = datetime.date(*map(int, s.split('_'))) is doing this: ‘s’ is a string (2019_03_22) and will separated by the split function at the positions ‘_’. Now map is taking the 3 parts of splitted string and applies a function to each of them. Function used is ‘int()’. Map then returns a so called ‘map object’. This can not be printed as it is. So we use the ‘*’ operator which is an ‘unpack operator’ in this case. I hope this sounds not too complicated.
23rd Mar 2019, 7:08 AM
Lothar
Lothar - avatar
+ 3
hi Raj, I have added some print statements to your code that shows what happens. import datetime import time s = time.strftime("%Y_%m_%d") print(s) print(type(s)) theday = datetime.date(*map(int, s.split('_'))) print(theday) print(type(theday)) previous_day = theday - datetime.timedelta(days=1) print(previous_day) output: 2019_03_22 <class 'str'> 2019-03-22 <class 'datetime.date'> 2019-03-21 In the first line after imports s is creared as a string Y M D with _ as separator. in the next line s wiil be split, converted to int and then converted to a datetime object. Then you can calculate with this object in the next line by subtracting -1. You can see what happens in the output. Hope this helps.
22nd Mar 2019, 12:14 PM
Lothar
Lothar - avatar
0
*map why do we use it?
22nd Mar 2019, 10:25 PM
Raj Charan