系统:Windows 7
语言版本:Anaconda3-4.3.0.1-Windows-x86_64
编辑器:pycharm-community-2016.3.2
- 这个系列讲讲Python对时间及日期的操作
- 今天讲讲如何将日期格式转化为字符串
- 涉及模块:datetime
Part 1:代码
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')
代码截图
![](https://img.haomeiwen.com/i7490971/1c3a31cadc6839db.png)
运行结果
![](https://img.haomeiwen.com/i7490971/c43842feb53e31fa.png)
Part 2:部分代码解读
-
now_time.strftime
,strftime,可以理解为string format的time,即字符串格式的时间,因为后续还会讲一个函数strptime,不要混淆 - 格式化符号含义:
- %Y,4位数表示的年,例如2019
- %y,2位数表示的年,例如19
- %m,2位数表示的月,01-12
- %d,2位数表示的日,01-31
- %H,2位数表示的时,00-23,24小时制
- %I,2位数表示的时,01-12,12小时制
- %p,表示AM或者PM
- %M,2位数表示的分,00-59
- %S,2位数表示的秒,00-59
- %B,完整的月份表示
- %A,完整表示的周次
- %j,年内的第多少天,001-366
- %w,周内的第几天,0-6,从周日开始
本文为原创作品,欢迎分享朋友圈
常按图片识别二维码,关注本公众号
Python 优雅 帅气
![](https://img.haomeiwen.com/i7490971/89b1088ed19e2103.jpg)
网友评论