Does Python have a Real Time Clock, which can give the exact year, month, day, hour, minute, and second? How can I use it?
3 Answers
For date and time operations in Python you can import the datetime module. There are different functions related to date formatting, getting current date and time etc. Refer this documentation.
For example:
import datetime
now = datetime.datetime.now()
print("Current date and time:")
print(now.strftime("%Y-%m-%d %H:%M:%S"))
Comments
datetime.now()
That's it. It gives the current date and time up to microseconds. Use as you want.
For example, to set an alarm after 2 days by running a loop to check once per hour if the alarm time has been reached:
alarm_time = date.today() + timedelta(days=2)
while date.today() != alarm_time:
time.sleep(60 * 60)
# do here anything you want to do when alarm time is reached
Comments
You can try this:
from datetime import datetime
temp = datetime.now()
temp.year, temp.month, temp.day, temp.hour, temp.minute, temp.second would give your desired values separately:
timee = "{:04d}{:02d}{:02d} {:02d}:{:02d}:{:02d}".format(
temp.year, temp.month, temp.day, temp.hour, temp.minute, temp.second
)