1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python获取系统当前时间并转utc时间为绝对秒数_用Python将datetime.date转换为UTC时间戳...

python获取系统当前时间并转utc时间为绝对秒数_用Python将datetime.date转换为UTC时间戳...

时间:2021-12-11 13:20:50

相关推荐

python获取系统当前时间并转utc时间为绝对秒数_用Python将datetime.date转换为UTC时间戳...

如果d = date(, 1, 1)在世界协调时:>>> from datetime import datetime, date>>> import calendar>>> timestamp1 = calendar.timegm(d.timetuple())>>> datetime.utcfromtimestamp

(timestamp1)datetime.datetime(, 1, 1, 0, 0)

如果d在本地时区:>>> import time>>> timestamp2 = time.mktime(d.timetuple()) # DO NOT USE IT WITH UTC DATE>>> datetime.fromtimestamp(timestamp2)datetime.

datetime(, 1, 1, 0, 0)

timestamp1和timestamp2如果本地时区中的午夜与UTC中的午夜不是相同的时间实例,则可能有所不同。

转换datetime.date对象,表示以UTC格式表示的日期。calendar.timegm():DAY = 24*60*60 # POSIX day in seconds (exact value)timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * DAY

timestamp = (utc_date - date(1970, 1, 1)).days * DAY

根据UTC的说法,我怎样才能把日期转换成从时代开始的秒呢?

转换datetime.datetime(不是datetime.date对象,该对象已将时间以UTC的形式表示为相应的POSIX时间戳(afloat).

Python 3.3+from datetime import timezone

timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

注:有必要提供timezone.utc明示否则.timestamp()假设天真的datetime对象位于本地时区。

Python 3(<3.3)没有从datetime实例获取时间戳的方法,但是与datetime实例DT对应的POSIX时间戳可以轻松地按以下方式计算。对于一个天真的DT:timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)对于有意识的DT:timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1)

有趣的读物:划时代的时间与一天中的时间关于…之间的区别现在几点?和多少秒过去了?

Python 2

若要将上述代码用于Python 2,请执行以下操作:timestamp = (dt - datetime(1970, 1, 1)).total_seconds()

哪里timedelta.total_seconds()等于(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6启用真除法计算。from __future__ import divisionfrom datetime import datetime, timedeltadef totimestamp(dt, epoch=datetime(1970,1,1)):

td = dt - epoch # return td.total_seconds()

return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6 now = datetime.utcnow()print nowprint totimestamp(now)

输出量-01-08 15:34:10.0224031326036850.02

如何转换感知datetime对象为POSIX时间戳。assert dt.tzinfo is not None and dt.utcoffset() is not Nonetimestamp = dt.timestamp() # Python 3.3+

在Python 3上:from datetime import datetime, timedelta, timezone

epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)timestamp = (dt - epoch) / timedelta(seconds=1)integer_timestamp = (dt - epoch)

// timedelta(seconds=1)

在Python 2上:# utc time = local time - utc offsetutc_naive = dt.replace(tzinfo=None) - dt.utcoffset()timestamp =

(utc_naive - datetime(1970, 1, 1)).total_seconds()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。