Python Datetime.now() Tutorial

Python provides the datetime module for date and time-related operations. The datetime module can be used to get current date and time information like year, month, day, hour, minute, second, etc. The datetime.now() module is used to return current date and time information.

Import datetime

In order to use the datetime.now() method we should import the datetime module with the import keyword like below.

import datetime

Get Current Date and Time

We can get the current date and time with the following code. Keep in mind that the datetime is a structure provided by the datetime module so we import is by using the from datetime import datetime . We return current date and time information into the current_date_time variable.

from datetime import datetime

current_date_time = datetime.now()

print(current_date_time)

Using Current Date and Time Attributes

The datetime.now() method returns an object which contains all date and time-related attributes or values. We can use the dot notation in order to access specific attributes like a year, month, day, hour, minute, second, microsecond, etc.

from datetime import datetime

current_date_time = datetime.now()

print(current_date_time.year)

print(current_date_time.month)

print(current_date_time.day)

print(current_date_time.hour)

print(current_date_time.minute)

print(current_date_time.second)

print(current_date_time.microsecond)

Get Current Date and Time for a Specific Time Zone

The datetime.now() can be used to get current date and time information about a specific zone. We should provide the zone information by using the pytz module. In the following example, we get the current date and time information for the Istanbul which is Europe/Istanbul .

from datetime import datetime
import pytz

current_date_time = datetime.now(pytz.timezone("Europe/Istanbul"))

List All TimeZones and Shortnames

There are lots of timezones that can be hard to remember of find to use properly. We can use the pytz.all_timezones to print them and select a proper time zone.

from datetime import datetime
import pytz

print(pytz.all_timezones)

Leave a Comment