In this post, we will see how to get current date and time in python.
get current date
You can do it using datetime module, you need to import this module and use datetime.date.today() to get current date and you can extract various attrubutes such as year, month and day as below.
today = datetime.date.today() print(today) print ('ctime:', today.ctime()) print ('tuple:', today.timetuple()) print ('ordinal:', today.toordinal()) print ('Year:', today.year) print ('Mon :', today.month) print ('Day :', today.day)
ctime: Mon Nov 27 00:00:00 2017
tuple: time.struct_time(tm_year=2017, tm_mon=11, tm_mday=27, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=331, tm_isdst=-1)
Mon : 11
Day : 27
get current time
You can do it using datetime module, you need to import this module and use datetime.now().time() to get current time and you can extract various attrubutes such as hour, minute and second as below.
t=datetime.datetime.now().time() print(t) print('hour :', t.hour) print ('minute:', t.minute) print ('second:', t.second) print ('microsecond:', t.microsecond) print ('tzinfo:', t.tzinfo)
hour : 15
That’s all about getting current date and time in python.