1

I am trying to write a function which takes a pandas dataframe of milliseconds data and converts it into datetime. However i am getting an error by name : AttributeError: 'numpy.int64' object has no attribute 'iat'

Now i have searched that .iat call is used to access element inside a pandas dataframe .

Dataframe consists of the following :

Time
1561912331018.00
1561912721486.00
1561977388732.00
1561899755951.00
1561897193639.00
1561982246953.00
1561977096883.00
1561919518921.00
1561942255704.00
1561939827253.00
1561965861054.00
1561960122342.00
1561949100949.00
1561962949812.00
def epoch_converter(data):

    for number , row_value in data.iteritems():

        number = data.loc[number].iat[0]
        import datetime
        number = number / 1000.0
        val = datetime.datetime.fromtimestamp(number).strftime('%Y-%m-%d %H:%M:%S.%f')
        print(val)


epoch_converter(time_val.Time)
Ali
  • 687
  • 8
  • 27
oyeshetty
  • 101
  • 1
  • 5
  • are you looking for this methode pandas.to_datetime¶ https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html – Ali Jul 03 '19 at 14:35
  • Possible duplicate of [Convert column in data.frame to date](https://stackoverflow.com/questions/33408636/convert-column-in-data-frame-to-date) – Ali Jul 03 '19 at 14:36
  • @PentaKill That's an R question. – cs95 Jul 03 '19 at 17:18
  • I may have solved the problem by removing the .iat[0] , however the value created in iteration is a "Nonetype" , how do i get it into a dataframe – oyeshetty Jul 04 '19 at 04:47
  • why did you did you use python tag – Ali Jul 04 '19 at 08:07

1 Answers1

1

Here is one way of doing it.

import datetime as dt
import pandas as pd


data = {
    "Time": [1561912331018.00, 1561912721486.00, 1561977388732.00, 1561899755951.00],
    "A": ["a", "b", "c", "d"],
}

df = pd.DataFrame(data)


def parse_millisecond_timestamp(ts: int) -> str:
    """Convert ms since Unix epoch to UTC datetime instance."""
    return dt.datetime.fromtimestamp(ts / 1000, tz=dt.timezone.utc).strftime(
        "%Y-%m-%d %H:%M:%S.%f"
    )

print(df)

           Time  A
0  1.561912e+12  a
1  1.561913e+12  b
2  1.561977e+12  c
3  1.561900e+12  d

# apply conversion to the 'Time' column
df["Time"] = df["Time"].apply(parse_millisecond_timestamp)

print(df)

                         Time  A
0  2019-06-30 16:32:11.018000  a
1  2019-06-30 16:38:41.486000  b
2  2019-07-01 10:36:28.732000  c
3  2019-06-30 13:02:35.951000  d
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179