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()
函数在日期和时间处理中非常有用,可以帮助我们轻松地在不同的日期和时间格式之间进行转换。