How to Get the Current Time in Python

Created
Modified

Using datetime Module

The datetime module supplies classes for manipulating dates and times. See the following example:

#!/usr/bin/python3
# -*- coding: utf8 -*-

# Import module
import datetime
from zoneinfo import ZoneInfo

now = datetime.datetime.now()
print(now)

tz = ZoneInfo("Etc/UTC")
utc = datetime.datetime.now(tz=tz)
print(utc)
2022-04-27 10:48:46.195335
2022-04-27 02:48:46.195834+00:00

Construct a datetime from time.time() and optional time zone info.

Using time Module

You can use time.gmtime() method to convert a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero. If secs is not provided or None, the current time as returned by time() is used. For example,

#!/usr/bin/python3
# -*- coding: utf8 -*-

# Import module
import time

# time.gmtime([secs])
now = time.gmtime()

f = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
print(f)
2022-04-27 02:58:35

This is UTC time, different from datetime module. Use the function localtime() instead of the gmtime() to get your local time.

time.strftime Method

The following directives can be embedded in the format string:

Directives:
%a
Locale’s abbreviated weekday name.
%A
Locale’s full weekday name.
%b
Locale’s abbreviated month name.
%B
Locale’s full month name.
%c
Locale’s appropriate date and timerepresentation.
%d
Day of the month as a decimal number [01,31].
%H
Hour (24-hour clock) as a decimal number[00,23].
%I
Hour (12-hour clock) as a decimal number[01,12].
%j
Day of the year as a decimal number [001,366].
%m
Month as a decimal number [01,12].
%M
Minute as a decimal number [00,59].
%p
Locale’s equivalent of either AM or PM.
%S
Second as a decimal number [00,61].
%U
Week number of the year (Sunday as the firstday of the week) as a decimal number [00,53].All days in a new year preceding the firstSunday are considered to be in week 0.
%w
Weekday as a decimal number [0(Sunday),6].
%W
Week number of the year (Monday as the firstday of the week) as a decimal number [00,53].All days in a new year preceding the firstMonday are considered to be in week 0.
%x
Locale’s appropriate date representation.
%X
Locale’s appropriate time representation.
%y
Year without century as a decimal number[00,99].
%Y
Year with century as a decimal number.
%z
Time zone offset indicating a positive ornegative time difference from UTC/GMT of theform +HHMM or -HHMM, where H represents decimalhour digits and M represents decimal minutedigits [-23:59, +23:59].
%%
A literal '%' character.

Related Tags

#get# #time#