📜  datetime am pm python (1)

📅  最后修改于: 2023-12-03 15:14:37.355000             🧑  作者: Mango

DateTime in Python

In Python, the datetime module is used for working with dates and times. It provides several classes to work with dates and times such as datetime, date, time, timedelta, etc.

datetime Class

The datetime class is used to represent dates and times in Python. It provides various methods to work with dates and times. By default, it provides the current date and time.

from datetime import datetime

# Current Date and Time
now = datetime.now()
print("Current Date and Time:", now)
Formatting Datetime

The strftime() method is used to format the date and time in a particular format. The format codes are listed in the documentation.

from datetime import datetime

# Formatting Datetime
now = datetime.now()
formatted_date_time = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted Date and Time:", formatted_date_time)
date Class

The date class is used to work with dates in Python. It provides various attributes and methods to work with dates.

from datetime import date

# Today's Date
today = date.today()
print("Today's date:", today)

# Date Components
print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)

# Formatted Date
formatted_date = today.strftime("%d %b %Y")
print("Formatted Date:", formatted_date)
time Class

The time class is used to work with times in Python. It provides various attributes and methods to work with times.

from datetime import time

# Time Object
t = time(9, 30, 15)
print("Time:", t)

# Time Components
print("Hour:", t.hour)
print("Minute:", t.minute)
print("Second:", t.second)

# Formatted Time
formatted_time = t.strftime("%I:%M:%S %p")
print("Formatted Time:", formatted_time)
timedelta

The timedelta class is used to perform arithmetic operations on dates and times. It provides various methods to perform arithmetic operations such as addition, subtraction, etc.

from datetime import datetime, timedelta

# Current Time
now = datetime.now()

# Calculating Time Difference
diff = timedelta(days=5, hours=6, minutes=30)
new_date_time = now + diff

print("Current Date and Time:", now)
print("New Date and Time:", new_date_time)

In this article, we covered the basics of working with dates and times in Python using the datetime module. We covered the datetime, date, time, and timedelta classes along with their methods and attributes.