📜  python 获取时间戳 2020-04-23T12:00:00Z - Python (1)

📅  最后修改于: 2023-12-03 15:04:18.483000             🧑  作者: Mango

Python 获取时间戳 2020-04-23T12:00:00Z

在程序中,我们经常需要获取当前时间戳。Python提供了多种获取时间戳的方法,本文将介绍其中一种。

datetime 模块

Python标准库中的datetime模块提供了日期和时间的处理方法,其中的datetime类可以表示一个日期和时间的组合。我们可以使用该类中的timestamp()方法获取时间戳。

下面的代码演示了如何使用datetime模块获取特定时间(2020年4月23日12:00:00 UTC)的时间戳:

import datetime

time_str = '2020-04-23T12:00:00Z'
dt = datetime.datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%SZ')
timestamp = dt.timestamp()

print(timestamp)

输出结果:

1587643200.0

其中,strptime()方法将时间字符串转换成datetime对象,timestamp()方法将datetime对象转换成时间戳。

时间戳格式

时间戳通常以浮点数的形式表示,表示自UNIX纪元起的秒数。UNIX纪元是1970年1月1日 00:00:00 UTC。

如果需要将时间戳转换成可读性更好的日期格式,可以使用datetime模块的fromtimestamp()方法。下面的代码演示了如何将时间戳转换成日期格式:

import datetime

timestamp = 1587643200.0
dt = datetime.datetime.fromtimestamp(timestamp)

print(dt.strftime('%Y-%m-%d %H:%M:%S'))

输出结果:

2020-04-23 12:00:00

其中,strftime()方法将datetime对象转换成指定格式的时间字符串,'%Y-%m-%d %H:%M:%S'表示年份、月份、日期、小时、分钟、秒。可以根据需要调整该格式。