在 python 中获取 GMT 时间戳
Get GMT timestamp in python
我需要获取 GMT 时间戳,一天开始时的时间戳,一天结束时的时间戳,以下示例适用于今天 (2022-03-29):
Start of Day (Unix Timestamp): 1648512000
End of Day (Unix Timestamp): 1648598399
您可以在 https://www.epochconvert.com/
中查看
我的代码仅适用于一天开始的情况是下一个:
from datetime import datetime
start_date = datetime.today().strftime('%Y-%m-%d')
start_date += ' 00:00:00'
print(start_date)
timestamp = time.mktime(datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S").timetuple())
print(timestamp)
我的输出:
2022-03-29 00:00:00
1648533600.0
如您所见,这不是我正在等待的答案,该时间戳是我的当地时间,但我需要 GMT 时间戳作为答案(在本例中为 1648512000)
我该怎么做?
提前致谢!!
如果您想从 datetime 对象派生 Unix time,请确保设置时区/具有 aware datetime:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
print(now)
# 2022-03-29 23:34:51.701712+00:00
now_floored = datetime.combine(now.date(), now.time().min).replace(tzinfo=timezone.utc)
print(now_floored)
# 2022-03-29 00:00:00+00:00
now_floored_unix = now_floored.timestamp()
print(now_floored_unix)
# 1648512000.0
如果你不这样做(有天真的日期时间),Python 将使用 当地时间:
now = datetime.now()
now_floored = datetime.combine(now.date(), now.time().min)
print(now_floored.astimezone())
# 2022-03-29 00:00:00-06:00 # <- my current UTC offset is -6 hours
print(now_floored.timestamp(), (now_floored_unix-now_floored.timestamp())//3600)
# 1648533600.0 -6.0
我需要获取 GMT 时间戳,一天开始时的时间戳,一天结束时的时间戳,以下示例适用于今天 (2022-03-29):
Start of Day (Unix Timestamp): 1648512000
End of Day (Unix Timestamp): 1648598399
您可以在 https://www.epochconvert.com/
中查看我的代码仅适用于一天开始的情况是下一个:
from datetime import datetime
start_date = datetime.today().strftime('%Y-%m-%d')
start_date += ' 00:00:00'
print(start_date)
timestamp = time.mktime(datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S").timetuple())
print(timestamp)
我的输出:
2022-03-29 00:00:00
1648533600.0
如您所见,这不是我正在等待的答案,该时间戳是我的当地时间,但我需要 GMT 时间戳作为答案(在本例中为 1648512000)
我该怎么做? 提前致谢!!
如果您想从 datetime 对象派生 Unix time,请确保设置时区/具有 aware datetime:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
print(now)
# 2022-03-29 23:34:51.701712+00:00
now_floored = datetime.combine(now.date(), now.time().min).replace(tzinfo=timezone.utc)
print(now_floored)
# 2022-03-29 00:00:00+00:00
now_floored_unix = now_floored.timestamp()
print(now_floored_unix)
# 1648512000.0
如果你不这样做(有天真的日期时间),Python 将使用 当地时间:
now = datetime.now()
now_floored = datetime.combine(now.date(), now.time().min)
print(now_floored.astimezone())
# 2022-03-29 00:00:00-06:00 # <- my current UTC offset is -6 hours
print(now_floored.timestamp(), (now_floored_unix-now_floored.timestamp())//3600)
# 1648533600.0 -6.0