Python library defines a function that can be primarily used to get current time and date. now() function Return the current local date and time, which is defined under datetime module.
Syntax : datetime.now(tz)
Parameters :
tz : Specified time zone of which current time and date is required. (Uses Greenwich Meridian time by default.)
Returns : Returns the current date and time in time format.
Code #1 :
import datetime
current_time = datetime.datetime.now()
print ("Time now at greenwich meridian is : "
, end = "")
print (current_time)
|
Output :
Time now at greenwich meridian is : 2018-03-29 10:26:23.473031
Attributes of now() :
now() has different attributes, same as attributes of time such as year, month, date, hour, minute, second.
Code #2 : Demonstrate attributes of now().
import datetime
current_time = datetime.datetime.now()
print ("The attributes of now() are : ")
print ("Year : ", end = "")
print (current_time.year)
print ("Month : ", end = "")
print (current_time.month)
print ("Day : ", end = "")
print (current_time.day)
print ("Hour : ", end = "")
print (current_time.hour)
print ("Minute : ", end = "")
print (current_time.minute)
print ("Second : ", end = "")
print (current_time.second)
print ("Microsecond : ", end = "")
print (current_time.microsecond)
|
The attributes of now() are :
Year : 2018
Month : 3
Day : 26
Hour : 20
Minute : 9
Second : 4
Microsecond : 499806
Getting time of particular timezone :
Sometimes, the need is just to get the current time of a particular timezone. now() takes timezone as input to give timezone oriented output time. But these time zones are defined in pytz library.
Code #3 : Use of now() to handle specific timezone.
import datetime
import pytz
current_time = datetime.datetime.now(pytz.timezone('Asia / Calcutta'))
print ("The current time in india is : ")
print (current_time)
|
Output:
The current time in india is :
2018-03-29 03:09:33.878000+05:30
Note : Above code won’t work on online IDE due to absence of pytz module.
Application :
While developing any real world application, we might need to show real time of any timezone. now() function can do the work here very efficiently and easily.
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the
Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
15 Oct, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...