【问题标题】:Convert UTC Timestamp with milliseconds to Local Timestamp in HH:MM:SS format in Python Dataframe在 Python Dataframe 中将 UTC 时间戳与毫秒转换为 HH:MM:SS 格式的本地时间戳
【发布时间】:2020-04-19 19:07:31
【问题描述】:

我想将数据帧表中以毫秒为单位的 UTC 时间戳转换为只有 hh:mm:ss 格式的本地时间戳。这是我目前所做的。

代码

import pandas as pd
import requests
import json

from datetime import date
from datetime import datetime
import pytz

val_list = [['VAL_1', [[1587319860000, 62.468963623046875], [1587319920000, 62.46857198079427], [1587319980000, 62.46759033203125]]], ['VAL_2', [[1587319860000, 65.64366149902344], [1587319920000, 65.64424133300781], [1587319980000, 65.64410909016927]]], ['VAL_3', [[1587319860000, 72.03440348307292], [1587319920000, 72.03465779622395], [1587319980000, 72.03514099121094]]]]

index = [x[0] for x in val_list[0][1]]
val_dict = dict(val_list)
df = pd.DataFrame(val_dict, index=index)
for col in df.columns:
    df[col] = [elem[1] for elem in df[col]]
print(df)

输出

                   VAL_1      VAL_2      VAL_3
1587319860000  62.468964  65.643661  72.034403
1587319920000  62.468572  65.644241  72.034658
1587319980000  62.467590  65.644109  72.035141

代码

df.reset_index(level=0, inplace=True) #converting index to column name index
df.rename(columns={'index': 'TimeStamp'}, inplace=True) #renaming column name

df['TimeStamp'] = (pd.to_datetime(df['TimeStamp'], unit='ms')
                    .dt.tz_localize('utc')
                    .dt.tz_convert('Asia/Calcutta')) #Timezone

print(df)

输出

                  TimeStamp      VAL_1      VAL_2      VAL_3
0 2020-04-19 23:41:00+05:30  62.468964  65.643661  72.034403
1 2020-04-19 23:42:00+05:30  62.468572  65.644241  72.034658
2 2020-04-19 23:43:00+05:30  62.467590  65.644109  72.035141

我想删除 2020-04-19+05:30,只保留 23:41:00。任何建议都会有所帮助。

【问题讨论】:

标签: python python-3.x pandas dataframe datetime


【解决方案1】:

你可以试试这个:

[23]: df['time']=df['TimeStamp'].apply(lambda d: d.time())

In [24]: df
Out[24]:
                  TimeStamp      VAL_1      VAL_2      VAL_3      time
0 2020-04-19 23:41:00+05:30  62.468964  65.643661  72.034403  23:41:00
1 2020-04-19 23:42:00+05:30  62.468572  65.644241  72.034658  23:42:00
2 2020-04-19 23:43:00+05:30  62.467590  65.644109  72.035141  23:43:00

d.time() 基本上是从时间戳中提取时间分量

【讨论】:

  • 这里不需要使用apply,pandas.Series.dt.time可能效率更高
  • 使用了下面的代码并且它有效。 df["TimeStamp"] = df['TimeStamp'].apply(lambda d: d.time())
猜你喜欢
  • 1970-01-01
  • 2019-01-05
  • 2019-08-15
  • 2016-03-04
  • 2011-02-06
  • 2019-03-09
  • 1970-01-01
  • 2016-03-04
  • 2013-03-09
相关资源
最近更新 更多