How to get current year, month, day, etc. in python

By | 11 August, 2015

Ok, so you have been coding for quite some long hours this week and you suddenly realie you dont even know what day it is. Or even year (yes, it happens). Since you are on the python command line, here’s what you can do:

(ok, so the scenario could be slightly different…still, the method to retrieve the date parameters are relevant anyway)

from datetime importdatetime

currentYear = datetime.now().year
currentMonth = datetime.now().month
currentDay = datetime.now().day
currentHour = datetime.now().hour
currentMinute = datetime.now().minute
currentSecond= datetime.now().second
currentMicrosec = datetime.now().microsecond
currentWeekday = datetime.now().weekday() # weekday as integer - 0 is monday, 1 is tuesday, etc.

There’s lots of cool datetime calculations, methods and magic to be learned. Check the documentation link below.

Some reference reading:

Python docs: datetime — Basic date and time types
From blog “Programming By A Tool”