如何将日期转换为年份后的周数?

时间:2017-07-21 09:20:24

标签: python pandas datetime

我有以下代码:

from itertools import chain
from collections import defaultdict

# ------ for dict1 -------#

u1 = [1,2,3]
s1 = ['a','b','c']
x1 = [10,100,1000]

# ------ for dict2 -------#

u2 = [4,5,6]
s2 = ['d','e','f']
x2 = ['aa','bb','cc']

dict1 = {1:u1,2:s1,3:x1}
dict2 = {1:u2,2:s2,3:x2}

dict3 = defaultdict(list)
for a, b in chain(dict1.items(), dict2.items()):
     dict3[a].append(b)

#for a, b in dict3.items():
#    print(a, b)

print dict3

输出: enter image description here

我希望获得输出,例如:

df=pd.DataFrame(df['Created'])
Created=pd.DatetimeIndex(df['Created'])
df['CreatedDate']=Created.date
df['CreatedTime']=Created.time
df['CreatedDate']=pd.to_datetime(df['CreatedDate'], errors='coerce')
df['CreatedWW']=df['CreatedDate'].dt.week

任何人都可以分享我的想法吗?

1 个答案:

答案 0 :(得分:0)

您需要to_datetime参数format,然后strftime

这两个功能的所有格式都在http://strftime.org/

df = pd.DataFrame({'Created':['12/Apr/17 1:21 PM','27/Mar/17 11:06 AM']})
print (df)
              Created
0   12/Apr/17 1:21 PM
1  27/Mar/17 11:06 AM

df['new'] = pd.to_datetime(df['Created'], format='%d/%b/%y %H:%M %p').dt.strftime('%Y%V')
print (df)
              Created     new
0   12/Apr/17 1:21 PM  201715
1  27/Mar/17 11:06 AM  201713