温馨提示×

python strftime函数在时间处理中的技巧

小樊
93
2024-07-25 02:22:11
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

strftime函数是Python中用于格式化日期和时间的函数,可以将日期和时间对象转换为特定格式的字符串。以下是一些strftime函数在时间处理中的技巧:

  1. 格式化日期和时间:
import datetime

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

输出结果类似于:2021-10-26 14:30:00

  1. 获取星期几:
weekday = now.strftime("%A")
print(weekday)

输出结果为星期几的全称,比如:Tuesday

  1. 自定义格式化字符串:
custom_format = now.strftime("Today is %A, %B %d, %Y. The time is %I:%M %p.")
print(custom_format)

输出结果为类似于:Today is Tuesday, October 26, 2021. The time is 02:30 PM.

  1. 将时间戳转换为日期时间字符串:
timestamp = 1635225000
date_time = datetime.datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
print(date_time)

输出结果类似于:2021-10-26 14:30:00

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:Python处理unix timestamp的技巧

0