代码之家  ›  专栏  ›  技术社区  ›  Bill

有没有快速获取时间并转换为时间戳的方法?

  •  2
  • Bill  · 技术社区  · 6 年前

    有没有快速获取时间并转换为时间戳的方法?

    string="2018-10-17 12:31:46 UTC::@:[2771]:LOG: checkpoint starting: time"
    

    我可以用 split 得到前4名

    >>> string.split(":")[:3]
    ['2018-10-17 12', '31', '46 UTC']
    

    但是如何将它们合并回一个时间字符串并转换成时间戳呢?

    更新

    >>> date = parser.parse(':'.join(string.split(":")[:3]))
    >>> print(date)
    2018-10-17 12:31:46+00:00
    >>> timestamp = int(round(time.mktime(date.timetuple()) * 1000))
    >>> print(timestamp)
    1539743506000
    

    我使用下面的代码将日志上传到cloudwatch,它使用了我从日志字符串得到的日期/时间戳。

     logs = boto3.client('logs')
    
     date = parser.parse(':'.join(string.split(":")[:3]))
     timestamp = int(round(time.mktime(date.timetuple()) * 1000))
     event_response = logs.put_log_events(
        logGroupName=LOG_GROUP,
        logStreamName=LOG_STREAM,
        logEvents=[{
            'timestamp': timestamp,
            'message': string
        }],
        sequenceToken=str(next_sequence_token))
    

    coudwatch中真实日志的日期不同:

    enter image description here

    更新#2

    $ python3
    Python 3.7.0 (default, Oct  4 2018, 14:10:21)
    [Clang 10.0.0 (clang-1000.10.44.2)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from dateutil import parser
    >>> string="2018-10-17 12:31:46 UTC::@:[2771]:LOG: checkpoint starting: time"
    >>> date = parser.parse(':'.join(string.split(":")[:3]))
    >>> timestamp = int(round(date.timestamp() * 1000))
    >>> print(timestamp)
    1539779506000
    
    2 回复  |  直到 6 年前
        1
  •  4
  •   CodeIt Steve Tauber    6 年前

    我们可以用 join parser 模块。

    from dateutil import parser
    
    string="2018-10-17 12:31:46 UTC::@:[2771]:LOG: checkpoint starting: time"
    
    date = parser.parse(':'.join(string.split(":")[:3]))
    print (date)
    2018-10-17 12:31:46+00:00
    
        2
  •  1
  •   Brown Bear    6 年前

    对我来说,最简单的方法是 UTC:: dateutil :

    from dateutil import parser
    string="2018-10-17 12:31:46 UTC::@:[2771]:LOG: checkpoint starting: time"
    parser.parse(string.split(' UTC::')[0])
    

    结果是

    datetime.datetime(2018, 10, 17, 12, 31, 46)