How to get current date and time in python

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)

Output:

2017-11-27
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)
ordinal: 736660
Year: 2017
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)

Output:

15:14:56.946640
hour : 15
minute: 14
second: 56
microsecond: 946640
tzinfo: None

That’s all about getting current date and time in python.

Leave a Reply

Your email address will not be published. Required fields are marked *