首页 > 编程知识 正文

以 Python 获取当前时间

时间:2024-04-27 11:09:16 阅读:335178 作者:QIXX

无论是日常生活还是工作中,我们都会频繁地需要获取当前时间。Python 作为一种广泛应用的编程语言,提供了多种方法来获取当前时间。本文将从多个角度详细介绍在 Python 中如何获取当前时间,并提供相应的代码示例。

一、Python 内置模块——datetime

Python 标准库中自带了 datetime 模块,可以方便地获取当前时间和日期。

1、获取当前时间的日期和时间信息

import datetime

now = datetime.datetime.now()
print("当前时间:", now)
print("年份:", now.year)
print("月份:", now.month)
print("日期:", now.day)
print("小时:", now.hour)
print("分钟:", now.minute)
print("秒数:", now.second)

2、将时间格式化为字符串

import datetime

now = datetime.datetime.now()

# %Y 表示四位数的年份,例如:2021
# %m 表示两位数的月份,例如:08
# %d 表示两位数的日期,例如:15
# %H 表示两位数的小时,例如:18
# %M 表示两位数的分钟,例如:23
# %S 表示两位数的秒数,例如:45
time_str = now.strftime("%Y-%m-%d %H:%M:%S")
print("格式化后的时间:", time_str)

二、Python 内置模块——time

与 datetime 模块类似,Python 中还有一个 time 模块可以用来获取当前时间。与 datetime 不同的是,time 模块返回的是从 1970 年 1 月 1 日 00:00:00 开始计算的秒数,也被称为 Unix 时间戳。

1、获取当前时间的 Unix 时间戳

import time

timestamp = time.time()
print("当前时间的 Unix 时间戳为:", timestamp)

2、将时间戳转换为时间格式

import time

timestamp = time.time()

# 将时间戳转换为 struct_time 格式
time_tuple = time.localtime(timestamp)

# 将 struct_time 格式的时间转换为字符串格式
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time_tuple)
print("格式化后的时间:", time_str)

三、第三方库——arrow

除了 Python 内置模块外,还有一些第三方库可以方便地进行时间处理。其中最受欢迎的是 arrow,它提供了更加方便的 API 来进行时间操作。

1、获取当前时间

import arrow

now = arrow.now()
print("当前时间:", now)

2、将时间转换为指定格式的字符串

import arrow

now = arrow.now()

time_str = now.format("YYYY年MM月DD日 HH:mm:ss")
print("格式化后的时间:", time_str)

3、进行时间计算

import arrow

now = arrow.now()

# 向前推 2 天
two_days_ago = now.shift(days=-2)
print("两天前的时间:", two_days_ago)

# 向后推 3 小时
three_hours_later = now.shift(hours=3)
print("三小时后的时间:", three_hours_later)

# 计算两个时间之间的差
diff = three_hours_later - two_days_ago
print("两个时间之间的差为:", diff)

总结:

Python 提供了多种方法来获取当前时间,其中 datetime 和 time 是 Python 内置的模块,使用起来比较简单,但是灵活性和扩展性较差。而第三方库 arrow 提供了更加强大和方便的 API,可以帮助开发人员更好地进行时间操作。选择哪种方法,可以根据项目需求、开发经验和个人偏好来决定。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。