The following example queries and outputs the individual elements of a datetime
object, such as year, month, day, hours, minutes and seconds of the current time.
import datetime
dt = datetime.datetime.now()
print("current datetime: " + str(dt))
print("current year: " + str(dt.year))
print("current month: " + str(datetime.datetime.now().month))
print("current day: " + str(dt.day))
print("hours: " + str(dt.hour))
print("minutes: " + str(dt.minute))
print("seconds: " + str(dt.second))
dt
: This variable is assigned the current date and time using datetime.datetime.now()
. This function provides the current local datetime with precision up to the microsecond.str(dt)
) of the datetime object.dt
object. The year
attribute of a datetime object returns the year as an integer.datetime.datetime.now().month
, ensuring it prints the current month. This approach is slightly redundant since the month could have been extracted from dt
, similar to the year and day.dt
object, accessed through the day
attribute, which returns the day of the month as an integer.dt
. These are accessed using the hour
, minute
, and second
attributes respectively, which return each component as integers.This script effectively displays various components of the current date and time, useful in scenarios such as logging, timestamping events, or simply for displaying the current time on user interfaces.
current datetime: 2022-12-10 11:29:43.074482
current year: 2022
current month: 12
current day: 10
hours: 11
minutes: 29
seconds: 43
import datetime
dt = datetime.datetime.now()
day = dt.day
month = dt.month
year = dt.year
hour = dt.hour
minute = dt.minute
second = dt.second
print("Date: " + str(day) + "/" + str(month) + "/" + str(year))
print("Time: " + str(hour) + ":" + str(minute) + ":" + str(second))
dt
: This variable is assigned the current date and time captured by invoking datetime.datetime.now()
. This function returns the current local date and time with full precision including year, month, day, and time down to the second.day
, month
, year
: These variables extract the day, month, and year from the dt
object. Each of these attributes returns an integer representing their respective parts of the date.hour
, minute
, second
: Similarly, these variables store the hour, minute, and second components of the time from the dt
object. Each attribute extracts the corresponding part of the time as integers.day
, month
, and year
. This format is straightforward and widely used in many contexts for clear date representation.hour
, minute
, and second
.Date: 11/12/2022
Time: 9:31:2