Skip to content Skip to sidebar Skip to footer

Convert Current Time To Webkit/chrome 17-digit Timestamp

I'm writing some bash script that parses and modifies multiple preferences and bookmarks of Google Chrome in OS X. Some of the values require 17-digit WebKit timestamp to be provid

Solution 1:

Something like this?

from datetime import datetime, timedelta


defdate_from_webkit(webkit_timestamp):
    epoch_start = datetime(1601, 1, 1)
    delta = timedelta(microseconds=int(webkit_timestamp))
    return epoch_start + delta


defdate_to_webkit(date_string):
    epoch_start = datetime(1601, 1, 1)
    date_ = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
    diff = date_ - epoch_start
    seconds_in_day = 60 * 60 * 24return'{:<017d}'.format(
        diff.days * seconds_in_day + diff.seconds + diff.microseconds)


# Webkit to date
date_from_webkit('13116508547000000')  # 2016-08-24 10:35:47# Date string to Webkit timestamp
date_to_webkit('2016-08-24 10:35:47')  # 13116508547000000

Solution 2:

So after great solution provided by Tiger-222 I've found out about python's datetime microseconds (%f) and added it to my final bash script to get full available time resolution and, as a result, the precise WebKit timestamp. Might be helpful for someone, thus final code below:

function currentWebKitTimestamp {
    TIMESTAMP="$(python - <<END
from datetime import datetime

def calculateTimestamp():
    epoch = datetime(1601, 1, 1)
    utcnow = datetime.strptime(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'), '%Y-%m-%d %H:%M:%S.%f')
    diff = utcnow - epoch
    secondsInDay = 60 * 60 * 24
    return '{}{:06d}'.format(diff.days * secondsInDay + diff.seconds, diff.microseconds)
print calculateTimestamp()
END)"
    echo $TIMESTAMP
}
echo $(currentWebKitTimestamp)

The script embeds python in bash, just as I needed.


Important note:diff.microseconds do not have leading zeros here, so when below 100k, the way they're added they would result in corrupted timestamp, therefore the {:06d} format has been added to avoid this.

Post a Comment for "Convert Current Time To Webkit/chrome 17-digit Timestamp"