2

Does Python have a Real Time Clock, which can give the exact year, month, day, hour, minute, and second? How can I use it?

1
  • Python does not have a "Real Time Clock", but the computer it is running on may have one, and Python may access it through the operating system. Commented May 7 at 7:32

3 Answers 3

2

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"))
Sign up to request clarification or add additional context in comments.

Comments

1
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

1

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
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.