Files
Python_CookBook_repo/3.数字日期和时间/15.将字符串转成日期.py
2025-09-10 16:12:45 +08:00

22 lines
635 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from datetime import datetime, date
if __name__ == '__main__':
text = "2012-09-20"
# str -> time
y = datetime.strptime(text, "%Y-%m-%d")
z = datetime.now()
diff = z - y
print(diff)
# 如果你觉得不够美观,那就格式化一下
# time -> str
struct_time_str = datetime.strftime(y, "%A %B %d, %Y")
print(struct_time_str)
# 当然strptime这个函数的性能相当糟糕大量使用时如果考虑到效率问题还请自己动手
def parse_date(date_str):
y, m, d = date_str.split("-")
return datetime(int(y), int(m), int(d))
print(parse_date(text))