首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Python-时间及日期-02-时间转字符串

系统:Windows 7 语言版本:Anaconda3-4.3.0.1-Windows-x86_64 编辑器:pycharm-community-2016.3.2

  • 这个系列讲讲Python对时间及日期的操作
  • 今天讲讲如何将日期格式转化为字符串
  • 涉及模块: datetime

Part 1:代码

代码语言:javascript
复制
import datetime

# 转换成字符串
now_time = datetime.datetime.now()
print(now_time)
print(type(now_time))
print('\n')

str_time = now_time.strftime('%Y-%m-%d %H:%M:%S')
print(str_time)
print(type(str_time))
print('\n')

str_time = now_time.strftime('%y %m %d %I-%M-%S %p')
print(str_time)
print(type(str_time))
print('\n')

str_time = now_time.strftime('%B %d %A %j %w')
print(str_time)
print(type(str_time))
print('\n')

代码截图

运行结果

Part 2:部分代码解读

  1. now_time.strftimestrftime,可以理解为string formattime,即字符串格式的时间,因为后续还会讲一个函数strptime,不要混淆
  2. 格式化符号含义:
    • %Y,4位数表示的年,例如2019
    • %y,2位数表示的年,例如19
    • %m,2位数表示的月,01-12
    • %d,2位数表示的日,01-31
    • %H,2位数表示的时,00-23,24小时制
    • %I,2位数表示的时,01-12,12小时制
    • %M,2位数表示的分,00-59
    • %S,2位数表示的秒,00-59
    • %B,完整的月份表示
    • %A,完整表示的周次
    • %j,年内的第多少天,001-366
    • %w,周内的第几天,0-6,从周日开始
    • %p,表示AM或者PM
下一篇
举报
领券