판다 데이터 프레임의 타임스탬프 열에서 표준시를 제거하는 방법
Pandas가 forex DataFrame에 대해 시간대를 변경하는 것을 읽었지만 sqlite3 데이터베이스와의 상호 운용성을 위해 데이터 프레임 시간대의 시간 열을 단순하게 만들고 싶습니다.
내 판다 데이터 프레임의 데이터는 이미 UTC 데이터로 변환되었지만, 나는 이 UTC 시간대 정보를 데이터베이스에 유지하고 싶지 않습니다.
다른 출처에서 파생된 데이터의 샘플을 보면 다음과 같습니다.
print(type(testdata))
print(testdata)
print(testdata.applymap(type))
제공:
<class 'pandas.core.frame.DataFrame'>
time navd88_ft station_id new
0 2018-03-07 01:31:02+00:00 -0.030332 13 5
1 2018-03-07 01:21:02+00:00 -0.121653 13 5
2 2018-03-07 01:26:02+00:00 -0.072945 13 5
3 2018-03-07 01:16:02+00:00 -0.139917 13 5
4 2018-03-07 01:11:02+00:00 -0.152085 13 5
time navd88_ft station_id \
0 <class 'pandas._libs.tslib.Timestamp'> <class 'float'> <class 'int'>
1 <class 'pandas._libs.tslib.Timestamp'> <class 'float'> <class 'int'>
2 <class 'pandas._libs.tslib.Timestamp'> <class 'float'> <class 'int'>
3 <class 'pandas._libs.tslib.Timestamp'> <class 'float'> <class 'int'>
4 <class 'pandas._libs.tslib.Timestamp'> <class 'float'> <class 'int'>
new
0 <class 'int'>
1 <class 'int'>
2 <class 'int'>
3 <class 'int'>
4 <class 'int'>
그렇지만
newstamp = testdata['time'].tz_convert(None)
다음과 같은 오류가 표시됩니다.
TypeError: index is not a valid DatetimeIndex or PeriodIndex
열을 표준 시간대 단순 타임스탬프로 바꾸려면 어떻게 해야 합니까?
열은 다음과 같아야 합니다.datetime
dtype(예: 사용 후).그런 다음 을 사용하여 표준 시간대를 변경할 수 있습니다. 단순 타임스탬프는 표준 시간대에 해당합니다.None
:
testdata['time'].dt.tz_localize(None)
열이 인덱스()DatetimeIndex
가 아닌 경우 날짜/시간 함수에 액세스하는 데 액세스 도구를 사용해야 합니다.
데이터에 서로 다른 시간대 또는 서머타임 적용 전과 적용 후의 날짜 시간이 포함된 경우(예: psycopg2를 사용한 포스트지 데이터베이스에서 얻은 경우), 팬더 버전에 따라 최적의 변환 방법이 다음과 같은 일부 시나리오가 발생할 수 있습니다.
testdata['time'].apply(lambda x: x.replace(tzinfo=None))
이것이 작동하는 시나리오(사용법 참고)FixedOffsetTimezone
다른offset
의 사용 중에.dt.tz_localize(None)
하지 않음:
df = pd.DataFrame([
datetime.datetime(2018, 5, 17, 21, 40, 20, 775854,
tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=120, name=None)),
datetime.datetime(2021, 3, 17, 14, 36, 13, 902741,
tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=60, name=None))
])
pd.__version__
'0.24.2'
df[0].dt.tz_localize(None)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pandas/core/arrays/datetimes.py", line 1861, in objects_to_datetime64ns
values, tz_parsed = conversion.datetime_to_datetime64(data)
File "pandas/_libs/tslibs/conversion.pyx", line 185, in pandas._libs.tslibs.conversion.datetime_to_datetime64
ValueError: Array must be all same time zone
pd.__version__
'1.1.2'
df[0].dt.tz_localize(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.8/site-packages/pandas/core/generic.py", line 5132, in __getattr__
return object.__getattribute__(self, name)
File "/usr/local/lib/python3.8/site-packages/pandas/core/accessor.py", line 187, in __get__
accessor_obj = self._accessor(obj)
File "/usr/local/lib/python3.8/site-packages/pandas/core/indexes/accessors.py", line 480, in __new__
raise AttributeError("Can only use .dt accessor with datetimelike values")
AttributeError: Can only use .dt accessor with datetimelike values
타임스탬프가 이미 UTC에 있다고 말씀하신 것은 알지만, 방어적인 차원에서 타임스탬프(일부 또는 모두)가 다른 시간대에 있는 경우 코드에 영향을 주지 않도록 하는 것이 좋습니다.이는 비용이 전혀 들지 않으며 더욱 강력해질 것입니다.
newcol = testdata['time'].dt.tz_convert(None)
A
tz
의None
UTC로 변환되고 표준 시간대 정보가 제거됩니다.
타임스탬프에 포함된 시간대를 삭제하는 것보다 안전합니다.
다음과 같은 기능이 있습니다.
- 모든 pd 인스턴스가 있는 모든 열을 찾습니다.타임스탬프가 표시됩니다.
- 해당 열을 dtype datetime으로 변환합니다(시리즈에서 .dt 액세스자를 사용할 수 있도록 함).
- 모든 타임스탬프 현지화
dt.tz_localize(None)
UTC에 상대적으로 시간 이동을 유지합니다.
def remove_tz_from_dataframe(df_in):
df = df_in.copy()
col_times = [ col for col in df.columns if any([isinstance(x, pd.Timestamp) for x in df[col]])]
for col in col_times:
df[col] = pd.to_datetime(
df[col], infer_datetime_format=True)
df[col] = df[col].dt.tz_localize(None)
return df
언급URL : https://stackoverflow.com/questions/49198068/how-to-remove-timezone-from-a-timestamp-column-in-a-pandas-dataframe
'itsource' 카테고리의 다른 글
제한 없이 MySQL 오프셋 (0) | 2023.07.31 |
---|---|
DEBUG로 Oracle 패키지를 컴파일하면 어떤 영향을 받습니까? (0) | 2023.07.31 |
목록의 모든 항목과 일치하는 행 그룹 선택 (0) | 2023.07.31 |
보기에서 임시 테이블을 만들고 선택한 후 삭제할 수 있습니까? (0) | 2023.07.31 |
Oracle 역할에 부여된 권한 목록을 열거하려면 어떻게 해야 합니까? (0) | 2023.07.31 |