Skip to content

Python 时间相关函数速查 #29

Open
@bieberg0n

Description

@bieberg0n
Owner

引入模块

from datetime import datetime

当前时间

获取当前时间的datetime对象

now = datetime.now()

1 查看当前时间

now.ctime()
# 'Wed Nov 22 11:00:11 2017'

2 获取当前时间的时间戳(1970年到现在的秒数)

now.timestamp()
# 1511319722.87419

3 打印自定义格式的时间

(strftime:string format time 的缩写)

# 格式化成2009-03-20 11:45:39形式
now.strftime('%Y-%m-%d %H:%M:%S')
# '2017-11-22 11:11:35'

# 格式化成Sat Mar 28 22:24:24 2009形式
now.strftime('%a %b %d %H:%M:%S %Y')
# 'Wed Nov 22 11:11:55 2017'

时间格式转换

1 读取各种格式的时间字符串,转成 datetime 对象

(strptime:string parse time 的缩写)

# 读取‘Wed Nov 22 11:11:55 2017'
dt = datetime.strptime('Wed Nov 22 11:11:55 2017', '%a %b %d %H:%M:%S %Y')
# datetime.datetime(2017, 11, 22, 11, 11, 55)

2 时间戳转 datetime 对象

dt = datetime.fromtimestamp(1511322862.666288)

2 查看该时间的时间戳

dt.timestamp()
# 1511322862.666288

3 datetime对象转自定义格式的字符串

TODO


Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @bieberg0n

        Issue actions

          Python 时间相关函数速查 · Issue #29 · bieberg0n/blog