To get the current date and/or time in Python you can import datetime
from Python's datetime
module, then create a new datetime object and access the now()
method on that.
from datetime import datetime
now = datetime.now()
print(now)
# 2019-08-09 19:02:36.533074
You can then use the strftime()
(string format time) method to display the datetime object in whatever format you like.
Get time, day, month and year
# Access attributes
year = now.year # 2019
month = now.month # 8
day = now.day # 9
hour = now.hour # 19
minute = now.minute # 2
second = now.second # 36
microsecond = now.microsecond # 533074
# Format date and time
date = now.strftime('%Y-%m-%d')
print(date)
# 2019-08-09
time = now.strftime('%H:%M:%S %p')
print(time)
# 19:18:50 PM
word_month = now.strftime('%d %B %y')
print(word_month)
# 09 August 19
word_month_short = now.strftime('%-d %b')
print(word_month_short)
# 9 Aug
word_month_short_windows = now.strftime('%d %b').replace('0', '')
print(word_month_short_windows)
# 9 Aug (windows compatible)
locale_format = now.strftime('%c')
print(locale_format)
# Fri Aug 9 19:29:29 2019
week_num = now.strftime('%W')
print(week_num)
# 31 (Monday as first day of week)
weekday_num = now.strftime('%w')
print(weekday_num)
# 5 (Sunday is 0)
day_num_of_year = now.strftime('%j')
print(day_num_of_year)
# 221
To format a datetime object, you pass the strftime()
method a string argument to convey how you would like the datetime to be displayed. The %
operator followed by the appropriate date format directive character (e.g. %Y
for the 4 digit year) tells Python where you want certain date or time values to appear in the string. Other characters like -
or :
can be added to the string and will appear as is.