Here is a sample program for reading the current year, month, day, and time:
from datetime import datetime # Get the current date and timenow = () # Read year, month, day and timeyear = month = day = hour = minute = second = # Print the resultsprint("Current date:{}Year{}moon{}day".format(year, month, day)) print("Current time:{}:{}:{}".format(hour, minute, second))
This program is useddatetime
Modulardatetime
Class to get the current date and time. Then, by accessingdatetime
The properties of the object, such asyear
、month
、day
、hour
、minute
andsecond
to get the corresponding value. Finally, print out these values to show the current year, month, day, and time.
datetime
It is a module in the Python standard library that provides the function of processing dates and times. Here are somedatetime
Examples of common methods and usages of libraries:
- Import
datetime
Module:
from datetime import datetime, date, time
- Get the current date and time:
now = () print("Current date and time:", now)
- Get the current time:
current_time = ().time() print("Current time:", current_time)
- Create a specified date and time:
# Create a date objectspecified_date = date(2023, 5, 25) print("Specified date:", specified_date) # Create a time objectspecified_time = time(10, 30, 0) print("Specified time:", specified_time) # Create date and time objectsspecified_datetime = datetime(2023, 5, 25, 10, 30, 0) print("Specify date and time:", specified_datetime)
- Format date and time output:
formatted_date = ("%Y-%m-%d") print("Formatted date:", formatted_date) formatted_time = current_time.strftime("%H:%M:%S") print("Formatted time:", formatted_time) formatted_datetime = specified_datetime.strftime("%Y-%m-%d %H:%M:%S") print("Formatted date and time:", formatted_datetime)
The above are some commondatetime
The use of the library can be processed and operated according to specific needs.
This is the article about Python's use of datetime library to achieve time acquisition methods. For more related content on Python's datetime acquisition time, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!