Unix 纪元时间戳在 Python 中转换为 UTC 时区

Posted

技术标签:

【中文标题】Unix 纪元时间戳在 Python 中转换为 UTC 时区【英文标题】:Unix epoch timestamps converted to UTC timezone in Python 【发布时间】:2021-08-24 06:14:34 【问题描述】:

对于给定的年份,此代码返回一年的开始和结束的可读和 Unix 纪元时间。

如何简化此操作并将其默认为 UTC 时间而不是本地时区?我将不胜感激任何指针。谢谢。

#!/usr/bin/env python3

from datetime import datetime
import pytz

tz = pytz.utc
fmt = '%Y-%m-%d %H:%M:%S%z'

def unix_time(date):
    timestamp = datetime.strptime(date,fmt).strftime('%s')
    return str(timestamp) #unix timestamp

def first_of(year):
    first = str(datetime(year, 1, 1, tzinfo=tz)) #yyyy-01-01 00:00 
    times = [first, unix_time(first)] 
    return times

def last_of(year):
    last = str(datetime(year, 12, 31, 23, 59, tzinfo=tz)) #yyyy-12-31 23:59
    times = [last, unix_time(last)]
    return times

year = 2021
print(first_of(year), last_of(year), sep='\n')


【问题讨论】:

除了你根本不需要pytz(见deceze的回答),我们在标准库中有2021、Python 3.9和zoneinfo——所以pytz不应该不再使用。旧代码有一个 deprecation shim。 【参考方案1】:

只是不要在字符串、整数和datetime 对象之间进行所有不必要的转换,您的代码已经简单多了:

from datetime import datetime, timezone

year = 2021
first = datetime(year, 1, 1, tzinfo=timezone.utc)
last = datetime(year, 12, 31, 59, 59, 59, tzinfo=timezone.utc)

print(first, first.timestamp(), last, last.timestamp())

【讨论】:

以上是关于Unix 纪元时间戳在 Python 中转换为 UTC 时区的主要内容,如果未能解决你的问题,请参考以下文章

如何从 Unix 纪元时间转换并在 Python 中考虑夏令时?

如何在 Python 中将日期时间对象转换为自纪元(unix 时间)以来的毫秒数?

python iso8601日期格式与unix纪元日期时间之间的转换

如何在 C 中将 10131520 转换为 Unix 纪元时间?

Perl 将本地时间转换为 unix(纪元)时间

将长的 Unix 纪元时间戳转换为实际日期/时间