convert()
函數在日期和時間處理中的應用主要是將日期和時間從一種格式轉換為另一種格式
以下是 convert()
函數在日期和時間處理中的一些常見應用:
from datetime import datetime
date_string = "2021-06-01"
date_format = "%Y-%m-%d"
new_date_format = "%d/%m/%Y"
date_object = datetime.strptime(date_string, date_format)
new_date_string = date_object.strftime(new_date_format)
print(new_date_string) # Output: 01/06/2021
from datetime import datetime
time_string = "15:30:45"
time_format = "%H:%M:%S"
new_time_format = "%I:%M %p"
time_object = datetime.strptime(time_string, time_format)
new_time_string = time_object.strftime(new_time_format)
print(new_time_string) # Output: 03:30 PM
from datetime import datetime
datetime_string = "2021-06-01 15:30:45"
datetime_format = "%Y-%m-%d %H:%M:%S"
new_datetime_format = "%d/%m/%Y %I:%M %p"
datetime_object = datetime.strptime(datetime_string, datetime_format)
new_datetime_string = datetime_object.strftime(new_datetime_format)
print(new_datetime_string) # Output: 01/06/2021 03:30 PM
總之,convert()
函數在日期和時間處理中非常有用,可以幫助我們輕松地在不同的日期和時間格式之間進行轉換。