Bill
Bill

Reputation: 2973

any quick ways to get the time and convert to timestamp?

Any quick ways to get the time and convert to timestamp?

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

I can use split to get the first 4

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

But how to merge them back to a time string and convert to timestamp?

Update

@jezrael Use your solution, I convert it to timestamp, but seems the time is drifted.

>>> 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

I used below codes to upload logs to cloudwatch, it used the date/timestamp I got from log string.

 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))

The date with real logs in coudwatch is different:

enter image description here

Update #2

Finally I did with below codes, it needs python v3.3+

$ 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

Upvotes: 1

Views: 1999

Answers (2)

jezrael
jezrael

Reputation: 862611

We can use join with parser module.

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

Upvotes: 3

user8060120
user8060120

Reputation:

for me the simple way is split by UTC:: and use the parser from dateutil:

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

the result is

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

Upvotes: 1

Related Questions