1

Killing two birds with one stone, I have two questions

  1. How can I accurately call the current date? Current hour?
  2. And how can I accurately call a specific hour? Not specific to a day.
from datetime import date, datetime

current_time = datetime.utcnow() # Call current time
start_time = datetime.time.hour(17)
end_time = datetime.time.hour(20)
tdelaney
  • 73,364
  • 6
  • 83
  • 116

2 Answers2

3

Using the datetime module in Python

Examples given with Python 3

Get current time

from datetime import datetime

now = datetime.now()

current_time = now.strftime("%H:%M:%S") # H - hour, M- minute, S - second
print("Current Time =", current_time)

Get current hour

from datetime import datetime

now = datetime.now()

current_hour = now.strftime("%H") 
print("Current hour =", current_hour)

Get current date

from datetime import date

today = date.today()
print("Today's date:", today)

Likewise, use %S for second, %M for minute, and %H for hour. and %d for day, %m for month, and %Y for year.

Extras

Print date and time together

from datetime import datetime

# datetime object containing current date and time
now = datetime.now()
 
print("now =", now)

# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)

Print according to time-zone

from datetime import datetime
import pytz

tz_NY = pytz.timezone('America/New_York') 
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))

tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S

sources:

Date

Time

Also check out: Similar question

1

You were pretty close to an answer. Here we go.

import datetime

after importing the datetime module you just need to call:

current_time = datetime.datetime.now()

In case you wanna access the data you have the year, month, day, hour, minute, second, microsecond methods:

current_time.day # Will return 17

To specify a given hour you just have to a variable you have the datetime.time class.

An idealized time, independent of any particular day, assuming that every day has exactly 246060 seconds. (There is no notion of “leap seconds” here.) Attributes: hour, minute, second, microsecond, and tzinfo.

start_time = datetime.time(17, 25, 30) # (17:25:30)

And the same as before. Accessing data can be done by calling its methods.

start_time.hour # will return 17

Here you have the documentation: :) datetime module

Ed1123
  • 185
  • 1
  • 1
  • 11