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:
%aLocale’s abbreviated weekday name.%ALocale’s full weekday name.%bLocale’s abbreviated month name.%BLocale’s full month name.%cLocale’s appropriate date and timerepresentation.%dDay of the month as a decimal number [01,31].%HHour (24-hour clock) as a decimal number[00,23].%IHour (12-hour clock) as a decimal number[01,12].%jDay of the year as a decimal number [001,366].%mMonth as a decimal number [01,12].%MMinute as a decimal number [00,59].%pLocale’s equivalent of either AM or PM.%SSecond as a decimal number [00,61].%UWeek 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.%wWeekday as a decimal number [0(Sunday),6].%WWeek 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.%xLocale’s appropriate date representation.%XLocale’s appropriate time representation.%yYear without century as a decimal number[00,99].%YYear with century as a decimal number.%zTime 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.