如何使用Timestamp()解析Python?

2024-09-30 08:28:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在遍历一个包含来自SQL数据库的数据的字典,我想计算user值出现在initial_date和{}之间的次数,但是,当我试图解析时间戳值时,我遇到了一些问题。这是我的密码

initial_date = datetime(2017,09,01,00,00,00)
ending_date  = datetime(2017,09,30,00,00,00)

dictionary sample that I got

sample = {'id': 100008222, 'sector name': 'BONGOX', 'site name': 'BONGO', 'region': 'EMEA', 
'open date': Timestamp('2017-09-11 00:00:00'), 'mtti': '16', 'mttr': '1', 'mttc': '2','user':'John D.'},
{'id': 100008234, 'sector name': 'BONGOY', 'site name': 'BONGO', 'region': 'EMEA', 
'open date': Timestamp('2017-09-09 12:05:00'), 'mtti': '1', 'mttr': '14', 'mttc': '7','user':'John D.'}
{'id': 101108234, 'sector name': 'BONGOA', 'site name': 'BONGO', 'region': 'EMEA', 
'open date': Timestamp('2017-09-01 10:00:00'), 'mtti': '1', 'mttr': '12', 'mttc': '1','user':'John C.'}
{'id': 101108254, 'sector name': 'BONGOB', 'site name': 'BONGO', 'region': 'EMEA', 
'open date': Timestamp('2017-09-02 20:00:00'), 'mtti': '2', 'mttr': '19', 'mttc': '73','user':'John C.'}

这是我用来计算user值出现在initial_date和{}之间的次数的代码

^{pr2}$

上面的代码不起作用,因为我遇到错误decoding to str: need a bytes-like object, Timestamp found

我有两个问题:

  1. 如何解析在这些字典中遇到的时间戳值?在
  2. 我在这篇文章中读到集合。计数器与其他方法相比,用于计算项目出现次数的方法较慢。如果想避免使用柜台。托收,如何计算这些日期之间user值出现的次数,以达到我想要的结果?在

Tags: nameiddatesiteopen次数regiontimestamp
2条回答

使用Timestamp.to_datetime()转换为datetime对象

Question: How can I parse this Timestamp value that I encountered in these dictionaries?

使用来自pandasclass Timestampe

from pandas import Timestamp
  1. 使用Counter()

    ^{pr2}$

    Output:

    2017-09-11 00:00:00 < 2017-09-30 00:00:00
    2017-09-09 12:05:00 < 2017-09-30 00:00:00
    2017-09-01 10:00:00 < 2017-09-30 00:00:00
    2017-09-02 20:00:00 < 2017-09-30 00:00:00
    Counter({'John C.': 2, 'John D.': 2})
    

Question: If want to avoid using Counter.Collections, how can I achieve my desired result of counting

  1. 没有Counter()

    # Initialize a Dict object
    c = {}
    # Iterate data
    for s in sample:
        # Get a datetime from Timestamp
        dt = s['open date'].to_pydatetime()
    
        # Compare with ending_date
        if dt < ending_date:
            # Add key=s['user'] to Dict if not exists
            c.setdefault(s['user'], 0)
    
            # Increment the Dict key=s['user']
            c[s['user']] += 1
    print(c)
    

    Output:

    {'John D.': 2, 'John C.': 2}
    

用Python:3.4.2测试

相关问题 更多 >

    热门问题