python中使用时间戳timestamp

python中的time.time()就是时间戳

代码:

import time
time_stamp = time.time()
print(time_stamp)

time_array = time.localtime(time_stamp)
other_way_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
print(other_way_time)

结果:
1610608539.8310502
2021-01-14 15:15:39

当然很多时候时间戳会记录整数,需要进行int

import time
time_stamp = int(time.time())
print(time_stamp)

结果:
1610608841

### Python 中的时间戳操作 #### 时间戳的概念 时间戳是一个表示日期和时间的数值,通常以秒为单位。它代表自纪元以来经过的时间,即从1970年1月1日午夜(UTC)到指定时间所经历的秒数[^3]。 #### 获取当前时间戳Python中可以使用`time`模块中的`time()`函数来获取当前时间戳: ```python import time current_timestamp = time.time() print(f"Current timestamp: {current_timestamp}") ``` 这段代码会打印出当前时刻对应的时间戳值[^2]。 #### 将时间戳转换成可读格式 为了使时间戳更易于阅读,可以通过`strftime()`方法将其转化为字符串形式的人类友好型表达方式: ```python readable_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(current_timestamp)) print(f"Readable format of the current timestamp is: {readable_time}") ``` 这里使用了`localtime()`把浮点数形式的时间戳转成了struct_time对象,再通过`strftime()`定义输出样式[^1]。 #### 计算两个时间戳之间的差异 如果想要知道两段时间之间相差多少秒,则可以直接做减法运算得到结果;对于更加复杂的场景比如求取天数差距等则可能需要用到datetime模块辅助完成: ```python from datetime import timedelta timestamp_early = 1609459200 # Example early timestamp (January 1st, 2021) timestamp_later = 1640995200 # Example later timestamp (January 1st, 2022) difference_in_seconds = timestamp_later - timestamp_early difference_in_days = difference_in_seconds / (60 * 60 * 24) print(f"Difference in seconds between two timestamps: {difference_in_seconds} s") print(f"Difference in days between two timestamps: {int(difference_in_days)} day(s)") ``` 上述例子展示了如何简单地计算两个不同时间点间存在的具体差别。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值