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