Get the current time in Python

1 min read

To create a datetime object with the current date and time you can simply use Python's datetime module and now() method. You can then use the strftime() (string format time) method to display the datetime object in whatever format you like.

Here's an example of how to create a datetime object with the current datetime, access it's various attributes and display the time in a few common formats. Below this you'll find more information on how to format the appearance of datetime objects.

from datetime import datetime

now =
# 2019-08-09 19:02:36.533074

# Access attributes
year = now.year # 2019
month = now.month # 8
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')
# 2019-08-09

time = now.strftime('%H:%M:%S %p')
# 19:18:50 PM

word_month = now.strftime('%d %B %y')
# 09 August 19

word_month_short = now.strftime('%-d %b')
# 9 Aug

word_month_short_windows = now.strftime('%d %b').replace('0', '')
# 9 Aug (windows compatible)

locale_format = now.strftime('%c')
# Fri Aug 9 19:29:29 2019

week_num = now.strftime('%W')
# 31 (Monday as first day of week)

weekday_num = now.strftime('%w')
# 5 (Sunday is 0)

day_num_of_year = now.strftime('%j')
# 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.

Author picture
Rhett Trickett

Founder at Able

@rhett RhettTrickett rhetttrickett

Join the discussion

Able is a developer community where people build their coding knowledge and careers.

Join with GitHub Join with Twitter