python如何获取当前时间字符串

python如何获取当前时间字符串

作者:Joshua Lee发布时间:2026-01-14阅读时长:0 分钟阅读次数:12

用户关注问题

Q
如何用Python获得当前时间的格式化字符串?

我想在Python程序中获取当前时间,并将其转换成特定格式的字符串,该怎么实现呢?

A

使用datetime模块格式化当前时间字符串

可以使用Python内置的datetime模块,通过datetime.datetime.now()获取当前时间,然后调用strftime()方法将时间转为字符串,例如:

import datetime
current_time = datetime.datetime.now()
time_string = current_time.strftime("%Y-%m-%d %H:%M:%S")
print(time_string)

这样就能得到格式为“年-月-日 时:分:秒”的时间字符串。

Q
有没有更简单的方法在Python中获取当前时间字符串?

除了使用datetime模块,我还能更快捷地得到当前时间的字符串吗?

A

快速使用time模块获取当前时间字符串

可以利用Python的time模块,通过time.strftime()直接获取格式化的时间字符串,比如:

import time
time_string = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(time_string)

这种方法同样可以得到当前时间的格式化字符串,适合快速需求。

Q
如何自定义Python中获取当前时间字符串的格式?

我想将当前时间格式定制成比如“2024年06月15日 14时30分”,要怎么设置格式化代码?

A

通过strftime自定义时间字符串格式

strftime函数支持多种格式化符号,可以自由组合要求的时间字符串格式。例如,要得到“2024年06月15日 14时30分”,可写成:

import datetime
now = datetime.datetime.now()
custom_format = now.strftime("%Y年%m月%d日 %H时%M分")
print(custom_format)

这样就能得到想要的中文时间格式。