Python strftime() function is present in datetime and time modules to create a string representation based on the specified format string.

datetime和time模块中提供了Python strftime()函数,用于基于指定的格式字符串创建字符串表示形式。

Python strftime() (Python strftime())

  • Python datetime module strftime() function and time module strftime() function behaves exactly the same. However, their syntax is slightly different.

    Python datetime module strftime() function syntax is:

    datetime_object.strftime(format_str)

    Python time module strftime() function syntax is:

    This function converts a tuple or struct_time object to a string as specified by the format argument. If ‘time_object’ is not provided, the current time as returned by localtime() is used. The format argument must be a string.

    Python datetime模块 strftime()函数的语法为:

    datetime_object.strftime(format_str)

    Python时间模块 strftime()函数的语法为:

    此函数将元组或struct_time对象转换为format参数指定的字符串。 如果未提供“ time_object”,则使用localtime()返回的当前时间。 format参数必须是字符串。

  • For time objects (datetime.time()), the format codes for the year, month, and day should not be used, as time objects have no such values. If they’re used anyway, 1900 is substituted for the year, and 1 for the month and day.对于时间对象(datetime.time()),不应使用年,月和日的格式代码,因为时间对象没有此类值。 如果仍然使用它们,则用1900代替年份,用1代替月份和日期。
  • For date objects (datetime.date()), the format codes for hours, minutes, seconds, and microseconds should not be used, as date objects have no such values. If they’re used anyway, 0 is substituted for them.对于日期对象(datetime.date()),不应使用小时,分钟,秒和微秒的格式代码,因为日期对象没有此类值。 如果仍然使用它们,则将0替换为它们。

Python strftime()格式指令 (Python strftime() format directives)

Following table list outs the most commonly used formatting directive that can be used in format string.

下表列出了可以在格式字符串中使用的最常用的格式指令。

.tg {border-collapse:collapse;border-spacing:0;border-color:#999;} .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#444;background-color:#F7FDFA;} .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#fff;background-color:#26ADE4;} .tg .tg-hmp3{background-color:#D2E4FC;text-align:left;vertical-align:top} .tg .tg-md4w{background-color:#D2E4FC;text-align:left} .tg .tg-s268{text-align:left} .tg .tg-0lax{text-align:left;vertical-align:top}.tg {border-collapse:collapse;border-spacing:0;border-color:#999;} .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#444;background-color:#F7FDFA;} .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#fff;background-color:#26ADE4;} .tg .tg-hmp3{background-color:#D2E4FC;text-align:left;vertical-align:top} .tg .tg-md4w{background-color:#D2E4FC;text-align:left} .tg .tg-s268{text-align:left} .tg .tg-0lax{text-align:left;vertical-align:top}

Directive Description Example Output
%a Weekday as locale’s abbreviated name. Sun, Mon, …, Sat (en_US)
So, Mo, …, Sa (de_DE)
%A Weekday as locale’s full name. Sunday, Monday, …, Saturday (en_US)
Sonntag, Montag, …, Samstag (de_DE)
%w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 0, 1, 2, 3, 4, 5, 6
%d Day of the month as a zero-padded decimal number. 01, 02, …, 31
%b Month as locale’s abbreviated name. Jan, Feb, …, Dec (en_US)
Jan, Feb, …, Dez (de_DE)
%B Month as locale’s full name. January, February, …, December (en_US)
Januar, Februar, …, Dezember (de_DE)
%m Month as a zero-padded decimal number. 01, 02 … 12
%y Year without century as a zero-padded decimal number. 01, 02, … 99
%Y Year with century as a decimal number. 0001, 0002, … , 9999
%H Hour (24-hour clock) as a zero-padded decimal number. 01, 02, … , 23
%I Hour (12-hour clock) as a zero-padded decimal number. 01, 02, … , 12
%p Locale’s equivalent of either AM or PM. AM, PM (en_US)
am, pm (de_DE)
%M Minute as a zero-padded decimal number. 01, 02, … , 59
%S Second as a zero-padded decimal number. 01, 02, … , 59
%f Microsecond as a decimal number, zero-padded on the left. 000000, 000001, …, 999999
Not applicable with time module.
%z UTC offset in the form ±HHMM[SS] (empty string if the object is naive). (empty), +0000, -0400, +1030
%Z Time zone name (empty string if the object is naive). (empty), UTC, IST, CST
%j Day of the year as a zero-padded decimal number. 001, 002, …, 366
%U Week number of the year (Sunday as the first day of the week) as a zero padded decimal number.
All days in a new year preceding the first Sunday are considered to be in week 0.
00, 01, …, 53
%W Week number of the year (Monday as the first day of the week) as a decimal number.
All days in a new year preceding the first Monday are considered to be in week 0.
00, 01, …, 53
%c Locale’s appropriate date and time representation. Tue Aug 16 21:30:00 1988 (en_US)
Di 16 Aug 21:30:00 1988 (de_DE)
%x Locale’s appropriate date representation. 08/16/88 (None)
08/16/1988 (en_US)
16.08.1988 (de_DE)
%X Locale’s appropriate time representation. 21:30:00 (en_US)
21:30:00 (de_DE)
%% A literal ‘%’ character. %
指示 描述 示例输出
%一个 工作日为语言环境的缩写名称。 周日,周一,…,周六(en_US)
因此,Mo,...,Sa(de_DE)
%一个 工作日为语言环境的全名。 周日,周一,…,周六(zh_CN)
桑塔格,蒙塔格,…,萨姆斯塔格(de_DE)
%w 以十进制数表示的工作日,其中0是星期日,6是星期六。 0、1、2、3、4、5、6
%d 月份中的一天,以零填充的十进制数字表示。 01,02,…,31
%b 月作为语言环境的缩写名称。 一月,二月,…,十二月(en_US)
一月,二月,…,德兹(de_DE)
%B 月作为语言环境的全名。 一月,二月,…,十二月(zh_CN)
Januar,Februar,...,Dezember(de_DE)
%m 以零填充的十进制数字表示的月份。 01,02…12
%y 无世纪的年份,为零填充的十进制数字。 01,02,…99
%Y 以世纪作为十进制数字的年份。 0001、0002,…,9999
%H 小时(24小时制),为补零的十进制数字。 01,02,…,23
%一世 小时(12小时制),为零填充的十进制数字。 01,02,…,12
%p 相当于AM或PM的语言环境。 上午,下午(en_US)
上午,下午(de_DE)
%M 分钟,为零填充的十进制数字。 01,02,…,59
%S 第二个为零填充的十进制数。 01,02,…,59
%F 微秒,十进制数,在左侧补零。 000000,000001,…,999999
不适用于时间模块。
%z UTC偏移量,格式为±HHMM [SS](如果对象是天真对象,则为空字符串)。 (空),+ 0000,-0400,+ 1030
%Z 时区名称(如果对象是天真对象,则为空字符串)。 (空),UTC,IST,CST
%j 一年中的一天,为零填充的十进制数字。 001,002,…,366
%U 一年中的周号(星期日为一周的第一天),以零填充的十进制数表示。
新年中第一个星期日之前的所有天均视为第0周。
00,01,…,53
%W 一年中的星期数(星期一为一周的第一天),以十进制数表示。
第一个星期一之前的新的一年中的所有天均视为在第0周。
00,01,…,53
%C 语言环境的适当日期和时间表示。 星期二八月16 21:30:00 1988(zh_CN)
Di 16 Aug 21:30:00 1988(de_DE)
%X 语言环境的适当日期表示形式。 88年8月16日(无)
1988年8月16日(zh_CN)
1988年8月16日(de_DE)
%X 语言环境的适当时间表示形式。 21:30:00(zh_CN)
21:30:00(de_DE)
%% 文字“%”字符。

Python strftime()示例 (Python strftime() example)

日期时间模块 (datetime module)

Let’s look at some examples of using strftime() function with datetime module.

让我们看一些将strftime()函数与datetime模块一起使用的示例。

import datetimedt = datetime.datetime.now()print('DateTime in Default Formatting:', dt)print('Formatted DateTime', dt.strftime("%m/%d/%y %H:%M:%S"))print("Current year:", dt.strftime("%Y"))
print("Month of year:", dt.strftime("%B"))
print("Week number of the year:", dt.strftime("%W"))
print("Weekday of the week:", dt.strftime("%w"))
print("Day of year:", dt.strftime("%j"))
print("Day of the month:", dt.strftime("%d"))
print("Day of week:", dt.strftime("%A"))

Output:

输出:

DateTime in Default Formatting: 2018-09-17 12:10:48.081992
Formatted DateTime 09/17/18 12:10:48
Current year: 2018
Month of year: September
Week number of the year: 38
Weekday of the week: 1
Day of year: 260
Day of the month: 17
Day of week: Monday

时间模块 (time module)

import time
seconds = time.time()
t = time.localtime(seconds)print('Time struct_time object:', t)
print('Time object with pre-defined formatting:', time.asctime(t))print('Formatted Time:', time.strftime("%m/%d/%y %H:%M:%S", t))print("Current year:", time.strftime("%Y", t))
print("Month of year:", time.strftime("%B", t))
print("Week number of the year:", time.strftime("%W", t))
print("Weekday of the week:", time.strftime("%w", t))
print("Day of year:", time.strftime("%j", t))
print("Day of the month:", time.strftime("%d", t))
print("Day of week:", time.strftime("%A", t))

时区 (TimeZone)

We know that the default datetime object doesn’t have timezone information, let’s see what is the output if we try to print its timezone.

我们知道默认的datetime对象没有时区信息,让我们看看尝试打印其时区的输出是什么。

print("TimeZone:", dt.strftime("%Z"))

Output: TimeZone:

输出:时TimeZone:

Let’s see the output with time module object.

让我们看一下带有时间模块对象的输出。

print("TimeZone:", time.strftime("%Z", t))

Output: TimeZone: IST

输出:时TimeZone: IST

We can use pytz module to create a timezone aware datetime object.

我们可以使用pytz模块创建一个时区感知的datetime对象。

import pytz
utc = pytz.utc
dt = datetime.datetime.now(utc)
print("TimeZone:", dt.strftime("%Z"))

Output: TimeZone: UTC

输出:时TimeZone: UTC

GitHub Repository.GitHub存储库中检出完整的python脚本和更多Python示例。

References: datetime strftime(), time strftime()

参考: datetime strftime() , 时间strftime()

翻译自: https://www.journaldev.com/23324/python-strftime

Python strftime()相关推荐

  1. Python eval()函数的使用

    Python eval()函数的使用 文章目录 一.官网给出的定义 1.eval() 方法的语法: 二.eval的作用 1.计算字符串中有效的表达式,并返回结果 2.将字符串转成相应的对象(如list ...

  2. Python xrange()函数

    Python xrange() function is used to generate a sequence of integers. This function is part of Python ...

  3. Python ord(),chr()函数

    Python ord() and chr() are built-in functions. They are used to convert a character to an int and vi ...

  4. Python bytearray()

    Python bytearray() function returns a bytearray object that contains the array of bytes from the inp ...

  5. Python complex()

    Python complex() function is used to create complex numbers. It's a built-in function that returns a ...

  6. Python Frozenset()

    Python frozenset is an unordered collection of distinct hashable objects. Frozenset is an immutable ...

  7. Python raw_input()

    Good day, learners. In our previous tutorial we learned about Python SimpleHTTPServer. In this tutor ...

  8. Python sorted()函数

    Python sorted() function returns a sorted list from the items in the iterable. Python sorted()函数从ite ...

  9. Python format()函数

    Python format() function is used to convert given object into string representation based on the pro ...

最新文章

  1. 判断手机是否弹出键盘,改变了手机页面高度,对应inputStatus的状态改变相关控件的大小和位置
  2. Angular.js
  3. VL09增强-冲销校验
  4. 【Leetocde | 24 】152. 乘积最大子序列
  5. 从SQL中相对于日期的特定周获取数据
  6. 选择JSF不选Struts的十大理由
  7. 论开学第二个月干了点啥
  8. 阿里云成长记的一篇文章《阿里云的这群疯子》
  9. 常用DNS列表(电信、网通)
  10. 优秀LOGO设计的规则
  11. python实战 爬取网易云评论信息
  12. 超声波模块工作原理分析及程序
  13. 学而思王帆初中语文教学视频
  14. 机关干部的21条人际关系准则
  15. Mathematica训练课(29)-对数函数相关操作
  16. openwrt passwall设置_和广告说再见!ADGUARD全客户端设置教程2.0
  17. c#连接西门子plc
  18. 2017华为校招汇总
  19. 最新CUDA环境配置(Win10 + CUDA 11.6 + VS2019)
  20. 男子裸辞,靠抓拍违章,月入过万!你支持吗?

热门文章

  1. 1588: [HNOI2002]营业额统计 - BZOJ
  2. 8.26~8.30-广州软件所-实习工作日记
  3. 咖啡口味介绍及存储方式
  4. [转载] python创建集合set()_Python 集合set()
  5. python 基础课程第三天
  6. Spring浅入浅出——不吹牛逼不装逼
  7. Android学习之多触点滑动
  8. (@WhiteTaken)设计模式学习——代理模式
  9. [cpp] 重载运算符规律总结
  10. C++之---class 的三种访问修饰符( public、private、protected )