美文网首页
Python-时间及日期-02-时间转字符串

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

作者: Data_Python_VBA | 来源:发表于2019-07-21 17:30 被阅读0次

微信公众号原文

系统: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')

代码截图

1.png

运行结果

2.png

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小时制
    • %p,表示AM或者PM
    • %M,2位数表示的分,00-59
    • %S,2位数表示的秒,00-59
    • %B,完整的月份表示
    • %A,完整表示的周次
    • %j,年内的第多少天,001-366
    • %w,周内的第几天,0-6,从周日开始

本文为原创作品,欢迎分享朋友圈

常按图片识别二维码,关注本公众号
Python 优雅 帅气


12x0.8.jpg

相关文章

网友评论

      本文标题:Python-时间及日期-02-时间转字符串

      本文链接:https://www.haomeiwen.com/subject/tkhvlctx.html