使matplotlib的date2num和num2date完美的反转 [英] Making matplotlib's date2num and num2date perfect inverses
问题描述
我正在尝试编写一个函数, plottm
和 unixtm
,它们之间来回转换正常的unix时间(自1970-01-01以来的秒)和Matplotlib的日期表示(从-1BC的最后一天起的天数或某事,浮点数)。
I'm trying to write a pair of functions, plottm
and unixtm
, which convert back and forth between normal unix time (seconds since 1970-01-01) and Matplotlib's date representation (days since the last day of -1BC or something, a float).
如果 plottm
和 unixtm
是正确的反转,那么这段代码将打印相同的日期/时间两次:
If plottm
and unixtm
were proper inverses then this code would print the same date/time twice:
import time, datetime
import matplotlib.dates as dt
# Convert a unix time u to plot time p, and vice versa
def plottm(u): return dt.date2num(datetime.datetime.fromtimestamp(u))
def unixtm(p): return time.mktime(dt.num2date(p).timetuple())
u = 1270000000
print datetime.datetime.fromtimestamp(u), "-->", \
datetime.datetime.fromtimestamp(unixtm(plottm(u)))
唉,这是一个小时(只发生在一些时间戳,否则我' d插入一个偏移量,并完成w
Alas, it's off by an hour (which only happens for some timestamps, otherwise I'd insert an offset and be done with it).
可能相关: Localtime的问题
更新:与Matplotlib不兼容的相关问题:将unixtime转换为datetime对象,然后再次(成对的时间转换函数)
UPDATE: Related question that isn't specific to Matplotlib: Convert a unixtime to a datetime object and back again (pair of time conversion functions that are inverses)
推荐答案
有 matplotlib.dates.epoch2num()/ num2epoch函数完全相同:
from datetime import datetime, timedelta
import matplotlib.dates as mpl_dt
matplotlib_epoch = datetime(1, 1, 1) # utc
posix_epoch = datetime(1970, 1, 1) # utc
DAY = 86400 # seconds
def plottm(u):
"""posix timestamp -> plot time"""
td = (datetime.utcfromtimestamp(u) - matplotlib_epoch)
return td.days + 1 + (1000000 * td.seconds + td.microseconds) / 1e6 / DAY
def unixtm(p):
"""plot time -> posix timestamp"""
td = timedelta(days=p-1)
return (matplotlib_epoch + td - posix_epoch).total_seconds()
def main():
f = datetime.utcfromtimestamp
u = 1270000000.1234567890
print(f(u))
print(mpl_dt.epoch2num(u))
print(plottm(u))
print(f(mpl_dt.num2epoch(mpl_dt.epoch2num(u))))
print(f(mpl_dt.num2epoch(plottm(u))))
print(f(unixtm(mpl_dt.epoch2num(u))))
print(f(unixtm(plottm(u))))
assert abs(mpl_dt.epoch2num(u) - plottm(u)) < 1e-5
p = 86401.234567890 / DAY
print(f(mpl_dt.num2epoch(p)))
print(f(unixtm(p)))
assert abs(mpl_dt.num2epoch(p) - unixtm(p)) < 1e-5
main()
输出
Output
2010-03-31 01:46:40.123457
733862.074076
733862.074076
2010-03-31 01:46:40.123453
2010-03-31 01:46:40.123453
2010-03-31 01:46:40.123453
2010-03-31 01:46:40.123453
0001-01-01 00:00:01.234566
0001-01-01 00:00:01.234566
这篇关于使matplotlib的date2num和num2date完美的反转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!