python中strftime函数_Python strftime()用法及代码示例

在Python中,日期和时间不是其自身的数据类型,而是名为

strftime()函数用于将日期和时间对象转换为其字符串表示形式。它需要一个或多个格式化代码输入,并返回字符串表示形式。

用法:

strftime(format)

返回值:它返回日期或时间对象的字符串表示形式。

格式代码列表:格式代码参考表。

指示

含义

输出格式

%a

Abbreviated weekday name.

Sun, Mon, …

%A

Full weekday name.

Sunday, Monday, …

%w

Weekday as a decimal number.

0, 1, …, 6

%d

Day of the month as a zero added decimal.

01, 02, …, 31

%-d

Day of the month as a decimal number.

1, 2, …, 30

%b

Abbreviated month name.

Jan, Feb, …, Dec

%B

Full month name.

January, February, …

%m

Month as a zero added decimal number.

01, 02, …, 12

%-m

Month as a decimal number.

1, 2, …, 12

%y

Year without century as a zero added decimal number.

00, 01, …, 99

%-y

Year without century as a decimal number.

0, 1, …, 99

%Y

Year with century as a decimal number.

2013, 2019 etc.

%H

Hour (24-hour clock) as a zero added decimal number.

00, 01, …, 23

%-H

Hour (24-hour clock) as a decimal number.

0, 1, …, 23

%I

Hour (12-hour clock) as a zero added decimal number.

01, 02, …, 12

%-I

Hour (12-hour clock) as a decimal number.

1, 2, … 12

%p

Locale’s AM or PM.

AM, PM

%M

Minute as a zero added decimal number.

00, 01, …, 59

%-M

Minute as a decimal number.

0, 1, …, 59

%S

Second as a zero added decimal number.

00, 01, …, 59

%-S

Second as a decimal number.

0, 1, …, 59

%f

Microsecond as a decimal number, zero added on the left.

000000 - 999999

%z

UTC offset in the form +HHMM or -HHMM.

%Z

Time zone name.

%j

Day of the year as a zero added decimal number.

001, 002, …, 366

%-j

Day of the year as a decimal number.

1, 2, …, 366

%U

Week number of the year (Sunday as the first day of the week). 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). All days in a new year preceding the first Monday are considered to be in week 0.

00, 01, …, 53

例:

# Python program to demonstrate

# strftime() function

from datetime import datetime as dt

# Getting current date and time

now = dt.now()

print("Without formatting", now)

# Example 1

s = now.strftime("%a %m %y")

print('\nExample 1:', s)

# Example 2

s = now.strftime("%A %-m %Y")

print('\nExample 2:', s)

# Example 3

s = now.strftime("%-I %p %S")

print('\nExample 3:', s)

# Example 4

s = now.strftime("%-j")

print('\nExample 4:', s)

输出:

Without formatting 2019-12-17 18:21:39.211378

Example 1:Tue-12-19

Example 2:Tuesday-12-2019

Example 3:6 PM 39

Example 4:351

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值