[英]Converting a string that has day of the year to datetime
I have a string column that looks like below: 我有一个字符串列,如下所示:
2018-24 7:10:0
2018-8 12:1:20
2018-44 13:55:19
The 24,8,44 that you see are the day of the year and not the date. 您看到的24、8、44是一年中的一天,而不是日期。
How can I convert this to datetime column in the below format ? 如何将其转换为以下格式的datetime列?
2018-01-24 07:10:00
2018-01-08 12:01:20
2018-02-13 13:55:19
I am unable to find anything related to converting day of the year ? 我找不到与一年中的转换日期相关的任何信息?
You need format string '%Y-%j %H:%M:%S'
您需要格式字符串
'%Y-%j %H:%M:%S'
In[53]:
import datetime as dt
dt.datetime.strptime('2018-44 13:55:19', '%Y-%j %H:%M:%S')
Out[53]: datetime.datetime(2018, 2, 13, 13, 55, 19)
For pandas
: 对于
pandas
:
In[59]:
import pandas as pd
import io
t="""2018-24 7:10:0
2018-8 12:1:20
2018-44 13:55:19"""
df = pd.read_csv(io.StringIO(t), header=None, names=['datetime'])
df
Out[59]:
datetime
0 2018-24 7:10:0
1 2018-8 12:1:20
2 2018-44 13:55:19
Use pd.to_datetime
and pass format
param: 使用
pd.to_datetime
并传递format
参数:
In[60]:
df['new_datetime'] = pd.to_datetime(df['datetime'], format='%Y-%j %H:%M:%S')
df
Out[60]:
datetime new_datetime
0 2018-24 7:10:0 2018-01-24 07:10:00
1 2018-8 12:1:20 2018-01-08 12:01:20
2 2018-44 13:55:19 2018-02-13 13:55:19
You can use dateutil.relativedelta for sum the day from the first day of years. 您可以使用dateutil.relativedelta作为年份的第一天的总和。
example: 例:
from datetime import datetime
from dateutil.relativedelta import relativedelta
datetime.now()+ relativedelta(days=5)
The documentation at strftime.org identifies the %j
format specifier as handling day of the year. strftime.org上的文档将
%j
格式说明符标识为一年中的某天。 I don't know whether it's available on all platforms, but my Mac certainly has it. 我不知道它是否在所有平台上都可用,但是我的Mac肯定有它。
Use time.strptime
to convert from string to datetime. 使用
time.strptime
将字符串转换为日期时间。 The output below has a newline inserted for reading convenience: 为了便于阅读,下面的输出中插入了换行符:
>>> time.strptime('2018-24 7:10:0', '%Y-%j %H:%M:%S')
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=24, tm_hour=7,
tm_min=10, tm_sec=0, tm_wday=2, tm_yday=24, tm_isdst=-1)
The time.strftime
formats datetimes, so you can get what you need by applying it to the output of strptime
: time.strftime
格式化日期时间,因此您可以通过将其应用于strptime
的输出来获得所需的strptime
:
>>> time.strftime('%Y-%m-%d %H:%M:%S',
... time.strptime('2018-24 7:10:0', '%Y-%j %H:%M:%S'))
'2018-01-24 07:10:00'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.