欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python获取系统时间为字符串_python怎么获取系统当前的时间

发布时间:2025/3/15 python 33 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python获取系统时间为字符串_python怎么获取系统当前的时间 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

python获取系统当前的时间的方法:可以利用datetime.datetime.now()函数来获取。具体方法:1、导入datetime包;2、获取当前的时间,如【curr_time = datetime.datetime.now()】。

具体方法:

1、导入包import datetime

2、获取当前的时间curr_time = datetime.datetime.now()  # 2019-07-06 14:55:56.873893

curr_time.year  # 2019

curr_time.month  # 7

curr_time.day  # 6 curr_time.hour  # 14

curr_time.minute  # 55

curr_time.second  # 56

curr_time.date()  # 2019-07-06

3、格式化

通过datetime.datetime.now(),我们获取到的时间格式为:2019-07-06 14:55:56.873893,类型:

我们可以使用strftime()转换成我们想要的格式。处理之后的返回的值为2019-07-06、07/06等目标形式,类型为strtime_str = curr_time.strftime("%Y-%m-%d")  # 2019-07-06

time_str = curr_time.strftime("%m/%d")  # 07/06

4、类型转换

时间一般通过:时间对象,时间字符串,时间戳表示

通过datetime获取到的时间变量,类型为:datetime,那么datetime与str类型如何互相转换呢?datetime-->str

time_str = datetime.datetime.strftime(curr_time,'%Y-%m-%d %H:%M:%S')  # 2019-07-06 15:50:12str-->datetime

time_str = '2019-07-06 15:59:58'

curr_time = datetime.datetime.strptime(time_str,'%Y-%m-%d %H:%M:%S')

与50位技术专家面对面20年技术见证,附赠技术全景图

总结

以上是生活随笔为你收集整理的python获取系统时间为字符串_python怎么获取系统当前的时间的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。