使用Pandas将字符串格式化为日期时间-指令有问题

5

我有一个字符串,它包含完整的年份和 ISO 年份周数(因为计算周数是从一年中的第一周开始的,所以有些年份有 53 周)。我想使用 pandas.to_datetime() 将其转换为 datetime 对象。所以我执行以下操作:

pandas.to_datetime('201145', format='%Y%W')

并且它返回:

Timestamp('2011-01-01 00:00:00')

这不是正确的。或者如果我尝试:
pandas.to_datetime('201145', format='%Y%V')

这告诉我%V是一个错误的指令。

我做错了什么?


1
我认为这可能是一个漏洞。https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior 或许值得在github上报告(也许是这个问题https://github.com/pydata/pandas/issues/10315,但我认为不同)。 - Andy Hayden
1个回答

2
我认为以下问题对你有用:如何反转 date.isocalender() 使用该问题中提供的函数,我会按照以下方式进行:
import datetime
import pandas as pd
def iso_year_start(iso_year):
    "The gregorian calendar date of the first day of the given ISO year"
    fourth_jan = datetime.date(iso_year, 1, 4)
    delta = datetime.timedelta(fourth_jan.isoweekday()-1)
    return fourth_jan - delta 

def iso_to_gregorian(iso_year, iso_week, iso_day):
    "Gregorian calendar date for the given ISO year, week and day"
    year_start = iso_year_start(iso_year)
    return year_start + datetime.timedelta(days=iso_day-1, weeks=iso_week-1)

def time_stamp(yourString):
    year = int(yourString[0:4])
    week = int(yourString[-2:])
    day = 1
    return year, week, day

yourTimeStamp = iso_to_gregorian( time_stamp('201145')[0] , time_stamp('201145')[1], time_stamp('201145')[2] )

print yourTimeStamp

然后运行该函数并将其作为日期时间对象附加到数据框中。

我从您指定的字符串中得到的结果是:

2011-11-07

我只是开玩笑说如果我无法解决这个问题,就必须将字符串解析为前四个和后两个字符。看来这确实是答案。谢谢! - user1566200
我在一个非常大的DataFrame上尝试了这个方法,但速度非常慢 - 大约60k行需要大约3分钟:time_convert_func = lambda x: iso_to_gregorian( time_stamp(x)[0] , time_stamp(x)[1], time_stamp(x)[2] ) 然后是 result = df['startdate'].astype(str).apply(time_convert_func) 有什么建议吗? - user1566200

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接