繁体   English   中英

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

[英]Unix epoch timestamps converted to UTC timezone in Python

对于给定的年份,此代码返回可读的和 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')


只是不要在字符串、整数和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())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM