1

Python で日付を年、月、日、時間 (時間) に分解する必要があります。

オブジェクトのリストがあり、各オブジェクトには日付プロパティがあります:

startDate=db.DateTimeProperty(auto_now_add=True)

date プロパティには、年、月、日、および時間がすべて 1 つに含まれています。

新しいネストされたリスト(辞書)を作成したい:

外側のリスト - 年 (入力日付の少なくとも 1 つに存在する) のリスト -> 各年の内部に月のリスト (入力日付の少なくとも 1 つにその年に存在する) -> この内部日 (月と同じ - 入力リストに存在する日) -> その中に時間 (時間) のリスト... それぞれがそれぞれのオブジェクトを指しています。

これが簡単に理解できることを願っています。

以下のリストを入力として取得した場合:

{obj1 -> (2000 Dec 18 9:00AM), obj2 -> (2000 Dec 19 1:00PM)}

それはそれらを一緒にクランプするので、私は持っています

(2000) -> (Dec) -> {(18) -> (9:00AM) -> obj1 ,(19) -> (1:00PM) -> obj2}

これが理にかなっていることを願っています..

基本的に、日付のあるイベントがたくさんあり、次のようにリストしたいと思います。

Year ->
Month(s) of interest->
Day(s) of interest->
(event times)
.
.
.

Another Year ->
Relevant Month(s) ->
Relevant Day(s) ->
(event times)
.
.
.

それ以外の:

(Event1 : complete date & time) , (Event2 : complete date & time) , (event3 : complete date & time)

ありがとう

4

2 に答える 2

1
class a: ## Using this class just to explain
    def __init__(self,y,m,d,t):
        self.y=y
        self.m=m
        self.d=d
        self.t=t


o1 = a(2000,12,18,9) ## Just assuming integers here. you can choose immutable objects here
o2 = a(2000,12,19,13)
o3 = a(2001,11,18,9)
o4 = a(2000,11,18,6)
o5 = a(2000,12,6,7)

l=[o1,o2,o3,o4,o5]


d={}

for o in l:
    if o.y not in d:
        d[o.y] = {}
    # print d
    if o.m not in d[o.y]:
        d[o.y][o.m]={}
    if o.d not in d[o.y][o.m]:
        d[o.y][o.m][o.d]={}
    if o.t not in d[o.y][o.m][o.d]:
        d[o.y][o.m][o.d][o.t]=o

より適切にフォーマットされた出力を生成してみることができます。

for k,v in d.items():
    for j,h in v.items():
        print k,j,h

私は次のように出力を取得します:

2000 11 {18: {6: <__main__.a instance at 0x0232E9E0>}}
2000 12 {18: {9: <__main__.a instance at 0x0232E940>}, 19: {13: <__main__.a instance at 0x0232E990>}, 6: {7: <__main__.a instance at 0x0232EA08>}}
2001 11 {18: {9: <__main__.a instance at 0x0232E9B8>}}
于 2012-09-05T16:57:38.197 に答える
0
ytree = {}
for obj in objects :
  dt = obj.time_field
  year = dt.year
  month = dt.month
  day = dt.day
  hour = dt.hour

  if not ytree.get(year):
    ytree[year] = {}
  if not ytree[year].get(month):
    ytree[year][month] = {}
  if not ytree[year][month].get(day):
    ytree[year][month][day] = {}
  if not ytree[year][month][day].get(hour):
    ytree[year][month][day][hour] = []
  ytree[year][month][day][hour].append(obj.event_name)
于 2012-09-05T16:59:41.897 に答える