温馨提示×

python strftime函数与strptime函数区别

小樊
101
2024-07-25 02:19:09
栏目: 编程语言

strftime函数用于将时间对象格式化为字符串,而strptime函数用于将字符串解析为时间对象。

strftime函数的参数是时间对象,返回一个格式化后的字符串,例如:

import datetime

now = datetime.datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)

strptime函数的参数是一个字符串和对应的格式化字符串,返回一个时间对象,例如:

import datetime

date_string = "2021-10-15"
date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d")
print(date_object)

总的来说,strftime函数是将时间对象转换为字符串,而strptime函数是将字符串转换为时间对象。

0