如何在Python中获取和使用当前时间
要在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
格式指令表