如何在Python中获取和使用当前时间

liftword4个月前 (12-16)技术文章47

要在Python应用程序中获取和输出当前时间的最直接方法是使用datetime模块中.now()方法。

>>> from datetime import datetime
>>> now = datetime.now()
>>> now
datetime.datetime(2023, 1, 4, 17, 0, 37, 261266)
>>> print(now)
2023-01-04 17:00:37.261266

直接显示now变量时,将获得你有可能看不懂的数字,如果print打印now变量,将会以正常的时间格式显示信息。

如果你只想要月份或年份,你可以从下面属性中进行选择。

>>> from datetime import datetime
>>> now = datetime.now()
>>>print(f"""
... {now.month = }
... {now.day = }
... {now.hour = }
... {now.minute = }
... {now.weekday() = }
... {now.isoweekday() = }""")

... now.month = 1
... now.day = 4
... now.hour = 17
... now.minute = 0
... now.weekday() = 2
... now.isoweekday() = 3

为了以更易读的的方式输出时间,可以使用datetime的.strftime()方法将代码格式化。

>>> from datetime import datetime
>>> now = datetime.now()
>>> now.strftime("%Y-%m-%d %H:%M")
'2023-01-04 17:00'
>>> now.strftime("%A, %d. %B %Y %I:%M%p")
'Wednesday, 04. January 2023 05:00PM'

datetime模块的.strptime()方法则可以按照特定时间格式将字符串转换为时间类型。

>>> from datetime import datetime
>>> now=datetime.strptime("4/1/23 17:20", "%d/%m/%y %H:%M")
>>> print(now)
2023-01-04 17:20:00

格式指令表

相关文章

python时间操作,最全封装,各种年月日加减、转换、获取

哈喽,我给大家封装了时间操作的工具,包含 年、月、日、时、分、秒增加指定时间,数字转换成时间,获取指定时间的年、月、日、时、分、秒,以及计算年月日的差值等,全网最全附源码,复制后即可引用。先看几个演...

Python 编程的“时间魔术”:掌握日期与时间的20+妙招

在Python中,管理时间和日期可能是我们经常面对的一项任务,而datetime模块正是帮我们处理这些问题的利器。datetime模块不仅让我们轻松搞定时间和日期的转换、操作,还能帮助我们应对日常工作...

了解何时使用函数以及何时在 Python 中选择类

Python 以其简单性和灵活性而闻名,它提供了多种构建代码的方法,其中函数和类是开发人员工具包中最常见的两种工具。函数和类在 Python 编程中都有其位置,但知道何时使用一个而不是另一个是编写高...

一日一技:Python中的timeit()方法

timeit()方法python中的timeit()方法, 它用于获取代码的执行时间。该库将代码语句运行一百万次,并提供从集合中花费的最短时间。这是一种有用的方法,有助于检查代码的性能。语法如下:ti...

Python办公自动化之Excel做表自动化

Excel与Python都是数据分析中常用的工具,本文将使用动态图(Excel)+代码(Python)的方式来演示这两种工具是如何实现数据的读取、生成、计算、修改、统计、抽样、查找、可视化、存储等数据...

Python编程基础:时间time模块 python time_ns

time模块提供了与时间相关的函数,本文介绍time模块的常用函数。获取时间戳:time()函数时间戳指自1970年1月1日0点0分0秒以来的总秒数(浮点数)。import time print(t...