Idiomatic way to parse POSIX timestamps in pandas?

2024/10/13 3:28:50

I have a csv file with a time column representing POSIX timestamps in milliseconds. When I read it in pandas, it correctly reads it as Int64 but I would like to convert it to a DatetimeIndex. Right now I first convert it to datetime object and then cast it to a DatetimeIndex.

In [20]: df.time.head()Out[20]: 
0    1283346000062
1    1283346000062
2    1283346000062
3    1283346000062
4    1283346000300
Name: timeIn [21]: map(datetime.fromtimestamp, df.time.head()/1000.)
Out[21]: 
[datetime.datetime(2010, 9, 1, 9, 0, 0, 62000),datetime.datetime(2010, 9, 1, 9, 0, 0, 62000),datetime.datetime(2010, 9, 1, 9, 0, 0, 62000),datetime.datetime(2010, 9, 1, 9, 0, 0, 62000),datetime.datetime(2010, 9, 1, 9, 0, 0, 300000)]In [22]: pandas.DatetimeIndex(map(datetime.fromtimestamp, df.time.head()/1000.))
Out[22]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2010-09-01 09:00:00.062000, ..., 2010-09-01 09:00:00.300000]
Length: 5, Freq: None, Timezone: None

Is there an idiomatic way of doing this? And more importantly is this the recommended way of storing non-unique timestmaps in pandas?

Answer

You can use a converter in combination with read_csv.

In [423]: d = """\
timestamp data
1283346000062 a
1283346000062 b
1283346000062 c
1283346000062 d
1283346000300 e
"""In [424]: fromtimestamp = lambda x:datetime.fromtimestamp(int(x) / 1000.)In [425]: df = pandas.read_csv(StringIO(d), sep='\s+', converters={'timestamp': fromtimestamp}).set_index('timestamp')In [426]: df.index
Out[426]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2010-09-01 15:00:00.062000, ..., 2010-09-01 15:00:00.300000]
Length: 5, Freq: None, Timezone: NoneIn [427]: df
Out[427]:data
timestamp
2010-09-01 15:00:00.062000    a
2010-09-01 15:00:00.062000    b
2010-09-01 15:00:00.062000    c
2010-09-01 15:00:00.062000    d
2010-09-01 15:00:00.300000    e
https://en.xdnf.cn/q/69576.html

Related Q&A

Apply function on each column in a pandas dataframe

How I can write following function in more pandas way:def calculate_df_columns_mean(self, df):means = {}for column in df.columns.columns.tolist():cleaned_data = self.remove_outliers(df[column].tolist()…

Compare 2 consecutive rows and assign increasing value if different (using Pandas)

I have a dataframe df_in like so:import pandas as pd dic_in = {A:[aa,aa,bb,cc,cc,cc,cc,dd,dd,dd,ee],B:[200,200,200,400,400,500,700,700,900,900,200],C:[da,cs,fr,fs,se,at,yu,j5,31,ds,sz]} df_in = pd.Data…

searching for k nearest points

I have a large set of features that looks like this:id1 28273 20866 29961 27190 31790 19714 8643 14482 5384 .... upto 1000 id2 12343 45634 29961 27130 33790 14714 7633 15483 4484 .... id3 ..... ....…

Why does del (x) with parentheses around the variable name work?

Why does this piece of code work the way it does?x = 3 print(dir()) #output indicates that x is defined in the global scope del (x) print(dir()) #output indicates that x is not defined in the glob…

How to concisely represent if/else to specify CSS classes in Django templates

In a Django template, Id like to add CSS classes to a DIV based on certain "conditions", for example:<div class="pkg-buildinfo {% if v.release.version == pkg.b.release.version %}activ…

LabelEncoder: How to keep a dictionary that shows original and converted variable

When using LabelEncoder to encode categorical variables into numerics, how does one keep a dictionary in which the transformation is tracked?i.e. a dictionary in which I can see which values became wh…

How to find hidden files inside image files (Jpg/Gif/Png) [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, argum…

How to open a simple image using streams in Pillow-Python

from PIL import Imageimage = Image.open("image.jpg")file_path = io.BytesIO();image.save(file_path,JPEG);image2 = Image.open(file_path.getvalue());I get this error TypeError: embedded NUL char…

SyntaxError: Non-UTF-8 code starting with \x82 [duplicate]

This question already has answers here:"SyntaxError: Non-ASCII character ..." or "SyntaxError: Non-UTF-8 code starting with ..." trying to use non-ASCII text in a Python script(7 an…

How to identify the CPU core ID of a process on Python multiprocessing?

I am testing Pythons multiprocessing module on a cluster with SLURM. I want to make absolutely sure that each of my tasks are actually running on separate cpu cores as I intend. Due to the many possibi…