Get year,month and day from python variable
10,201
Solution 1
you were close
import datetime
from datetime import date, timedelta
yesterday = date.today() - timedelta(1)
print (yesterday)
year = yesterday.year
month = yesterday.month
day=yesterday.day
print (year)
print (month)
print (day)
result is
2019-03-10
2019
3
10
Solution 2
You can also simplify your import statements like so:
from datetime import datetime, timedelta
yesterday = datetime.today() - timedelta(1)
print(yesterday)
year = yesterday.year
month = yesterday.month
day = yesterday.day
print(year)
print(month)
print(day)
You will get the output:
2019-03-10 21:19:36.695577
2019
3
10
Solution 3
You can use strftime
method
A simple example:
>>> from datetime import datetime
>>> now = datetime.utcnow()
>>> year_month_day_format = '%Y-%m-%d'
>>> now.strftime(year_month_day_format)
'2020-11-06'
>>> hour_minute_format = '%H:%M'
>>> now.strftime(hour_minute_format)
'22:54'
Hopping, it will help someones
Related videos on Youtube
Author by
mcadamsjustin
Updated on June 04, 2022Comments
-
mcadamsjustin almost 2 years
I'd like to get the break of a variable by year, month and day. Here's what I got:
import datetime from datetime import date, timedelta yesterday = date.today() - timedelta(1) print (yesterday) year = datetime.date.yesterday.year month = datetime.date.yesterday.month day=datetime.date.yesterday.day print (year) print (month) print (day)
I'm getting an error that datetime.date has no attribute. I'm a total noob at python and I'm stuck, any help is appreciated
-
mcadamsjustin about 5 yearsjust a note, I know I don't need the 'print (yesterday)' line, it was just testing for me
-
-
mcadamsjustin about 5 yearsthis works, Baris just beat you, thanks for the simplifying tip
-
Sébastien Lavoie about 5 yearsThat's how it is ;)... I will point out however that
yesterday
will also contain the time as shown in the output I added. From there, you can also access other attributes such asyesterday.hour
,yesterday.microsecond
,yesterday.minute
,yesterday.second
or even split individual fractions of time withyesterday.time()
and get the digit that corresponds to the day of the week withyesterday.weekday()
. -
Life is complex about 5 yearsyou could also strip the time information using -- yesterday.strftime('%d-%m-%Y')