我有一個帶有祖魯時區的字串格式的日期。我試圖用正則運算式擺脫“Z”字符,但我想有一種更有效的方法。
輸入:
|index | date | municipality
|------| --------------------|--------------
| 0 | 07.02.2021 1017Z | Algier
| 1 | 11.01.2019 1716Z | Abuja
| 2 | 23.02.2018 1002Z | Brüssel
| 3 | 19.07.2021 1459Z | Brüssel
| 4 | 26.11.2019 1049Z | Berlin
期望的結果:
|index | date | municipality
|------| --------------------|--------------
| 0 | 2021-02-17 | Algier
| 1 | 2019-01-11 | Abuja
| 2 | 2018-02-23 | Bruxelles
| 3 | 2021-07-19 | Bruxelles
| 4 | 2019-11-26 | Berlin
uj5u.com熱心網友回復:
不要擺脫 Z 字符,而是正確決議它。前任:
import pandas as pd
df = pd.DataFrame({'date': ['07.02.2021 1017Z', '11.01.2019 1716Z']})
df['date'] = pd.to_datetime(df['date'], format='%d.%m.%Y %H%M%z')
# df['date']
# Out[19]:
# 0 2021-02-07 10:17:00 00:00
# 1 2019-01-11 17:16:00 00:00
# Name: date, dtype: datetime64[ns, UTC]
請注意,設定format關鍵字是可選的,但明確指定它有助于提高一般可靠性。
如果您不想要它們,您也可以減少時間:
df['date'] = df['date'].dt.floor('D')
# df['date']
# Out[21]:
# 0 2021-02-07 00:00:00 00:00
# 1 2019-01-11 00:00:00 00:00
# Name: date, dtype: datetime64[ns, UTC]
...或格式化為字串:
df['date'].dt.strftime('%Y-%m-%d')
# 0 2021-02-07
# 1 2019-01-11
# Name: date, dtype: object
uj5u.com熱心網友回復:
我認為這會很好。此外,您可以在轉換期間使用日期進行一些計算。
from datetime import datetime as dt
# specify input and output formats
input_format = '%d.%m.%Y %H%MZ'
output_format = '%Y-%m-%d'
# input date
input_date = '07.02.2021 1017Z'
# convert input date to datetime object
date = dt.strptime(input_date, input_format)
# convert datetime object to string with output format
output_date = dt.strftime(date, output_format)
print(output_date)
# output: 2021-02-07
uj5u.com熱心網友回復:
Alexei 的方法也是一個很好的解決方案,我們可以將其代碼轉換為函式并使用它的示例:
from datetime import datetime as dt
df=pd.DataFrame()
dates=['07.02.2021 1017Z','11.01.2019 1716Z','23.02.2018 1002Z']
municipality=['Algier','Abuja','Brüssel' ]
df['date']=dates
df['municipality']=municipality
# specify input and output formats
input_format = '%d.%m.%Y %H%M%z'
output_format = '%Y-%m-%d'
# input date
input_date = '07.02.2021 1017Z'
def convert(input_date):
# convert input date to datetime object
date = dt.strptime(input_date, input_format)
# convert datetime object to string with output format
output_date = dt.strftime(date, output_format)
return(output_date)
df.date.apply(convert)
df

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/450963.html
