strftime是Python里将日期、时间格式化的一个工具方法
下面的代码片段将datetime转换成格式化后的string
from datetime import datetime
now = datetime.now()  # 当前日期
year = now.strftime("%Y")
print("年份:", year)
month = now.strftime("%m")
print("月份:", month)
day = now.strftime("%d")
print("天:", day)
print("星期:", now.strftime("%A"))
time = now.strftime("%H:%M:%S")
print("时间:", time)
date_time = now.strftime("%Y-%d-%m  %H:%M:%S")
print("当前日间日期是:", date_time)
以上代码打印出来的结果是:
年份: 2021 月份: 05 天: 13 星期: Thursday 时间: 09:33:11 当前日间日期是: 2021-13-05 09:33:11
强制使用指定的locale语言
以上看到输出星期几的时候,可能输出的是英文的Thursday,还有可能是上下午,月份等等,可能都是英文的,那我们需要输出中文的,可以指定所用的区域语言Locale
from datetime import datetime
import locale
now = datetime.now()  # 当前日期
locale.setlocale(locale.LC_TIME, 'zh_CN')  # 指定输出中文
print("星期:", now.strftime("%A"))
print("月份:", now.strftime("%B"))
格式化符号详解
Python的格式化符号和Java的有点不一样,整理如下:
| Directive | Meaning | Example | 
| %a | 本地简化星期名称 | 四,Sun, Mon, ... | 
| %A | 本地完整星期名称 | 星期四,Sunday, Monday, ... | 
| %w | 星期(0-6),星期天为星期的开始 | 0, 1, ..., 6 | 
| %d | 两位数表示的月内中的一天(01-31) | 01, 02, ..., 31 | 
| %-d | 月内中的一天(1-31) | 1, 2, ..., 30 | 
| %b | 本地简化的月份名称 | Jan, Feb, ..., Dec | 
| %B | 本地完整的月份名称 | 五月,January, February, ... | 
| %m | 两位数表示的月份 | 01, 02, ..., 12 | 
| %-m | 数字表示的月份 | 1, 2, ..., 12 | 
| %y | 两位数的年份表示(00-99) | 00, 01, ..., 99 | 
| %-y | 数字表示的年份 | 0, 1, ..., 99 | 
| %Y | 四位数的年份表示(000-9999) | 2013, 2019 etc. | 
| %H | 两位数表示的24小时制小时数(0-23) | 00, 01, ..., 23 | 
| %-H | 数字表示的24小时的小时数 | 0, 1, ..., 23 | 
| %I | 两位数表示的12小时制小时数(01-12) | 01, 02, ..., 12 | 
| %-I | 12小时制小时数(1-12) | 1, 2, ... 12 | 
| %p | 本地A.M.或P.M.的等价符 | 上午,AM, PM | 
| %M | 两位数表示的分钟数(00-59) | 00, 01, ..., 59 | 
| %-M | 数字表示的分钟数 | 0, 1, ..., 59 | 
| %S | 两位数表示的秒(00-59) | 00, 01, ..., 59 | 
| %-S | 数字表示的秒 | 0, 1, ..., 59 | 
| %f | 六位数表示的微秒 | 000000 - 999999 | 
| %z | 时差+0000, -0400 | +0000, -0400 | 
| %Z | 当前时区的名称 | |
| %j | 3位数表示的年内的一天(001-366) | 001, 002, ..., 366 | 
| %-j | 数字表示的年内的一天(1-366) | 1, 2, ..., 366 | 
| %U | 一年中的星期数(00-53)星期天为星期的开始 | 00, 01, ..., 53 | 
| %W | 一年中的星期数(00-53)星期一为星期的开始 | 00, 01, ..., 53 | 
| %c | 本地相应的日期表示和时间表示 | Mon Sep 30 07:06:05 2013 | 
| %x | 本地相应的日期表示 | 09/30/13,2021/05/13 | 
| %X | 本地相应的时间表示 | 07:06:05 | 
| %% | %号本身 | % | 
如何反向根据string转换成datetime请看:https://blog.terrynow.com/2021/05/15/python-strptime-parser-string-to-datetime/

文章评论