Skip to content

Getting the Current Time in Python

Python, Datetime, Time1 min read

Python provides several ways to get the current time, primarily through the datetime and time modules. This article will guide you through various methods to retrieve and format the current date and time in Python.

Using the datetime Module

The datetime module is commonly used for handling date and time in Python.

Getting Current Date and Time

1import datetime
2now =
3print(now) # Output: YYYY-MM-DD HH:MM:SS.ffffff

This gives you the current date and time down to microseconds.

Getting Only the Current Time

If you only need the current time:

1from datetime import datetime
2current_time =
3print(current_time) # Output: HH:MM:SS.ffffff

Using the time Module

Alternatively, you can use the time module, which is part of Python's standard library.

Formatting Date and Time

The time module allows for more control over formatting.

1from time import gmtime, strftime
2formatted_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())
3print(formatted_time) # Output: YYYY-MM-DD HH:MM:SS

This example uses gmtime() for UTC time. You can replace it with localtime() for local time.

Formatting Options

Both datetime and time modules provide ways to format the date and time output:

  • %Y-%m-%d %H:%M:%S - Standard date and time format.
  • %A, %B %d, %Y - Weekday, month, day, year.
  • Many other formatting options are available in the Python documentation.

Retrieving and formatting the current date and time in Python can be easily achieved with the datetime and time modules. Understanding these modules allows you to handle date and time effectively in your Python applications.