SoFunction
Updated on 2025-03-02

Python uses datetime library to implement the method of obtaining time

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 useddatetimeModulardatetimeClass to get the current date and time. Then, by accessingdatetimeThe properties of the object, such asyearmonthdayhourminuteandsecondto get the corresponding value. Finally, print out these values ​​to show the current year, month, day, and time.

datetimeIt is a module in the Python standard library that provides the function of processing dates and times. Here are somedatetimeExamples of common methods and usages of libraries:

  • ImportdatetimeModule:
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 commondatetimeThe 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!