Tip on Converting Cocoa Core Data to Unix Timestamp in Python

I was writing a script that reads out from an sqlite database, originally created by an iOS app. Being clueless about iOS development, I noticed that one of the columns had an unusual time stamp. Turns out that this is a Core Data time stamp, which is also sometimes labeled as 'Mac absolute time'.

Core Data is a storage framework to manage objects in iOS and OSX applications as part of the Cocoa API. In this framework, a Core Data timestamp is the number of seconds (or nanoseconds) since midnight, January 1, 2001, GMT. On the other hand, the Unix timestamp is the number of seconds since January 1, 1970 GMT.

A Cocoa timestamp of 590517794 seconds or 590517794000000000 nano seconds represents the date time of Wednesday, September 18, 2019 4:43:14 PM. If mistakenly assumed as a Unix timestamp, the value would be represented as Saturday, September 17, 1988 4:43:14 PM.

To do the conversion, you can simply generate a Unix time stamp for January 1, 2001 and add up that value with the Core Data timestamp you have. Here is a quick example in Python:

from datetime import datetime
from time import mktime

coredata_timestamp = 590517794

coredata_start_date = datetime(2001, 1, 1, 0, 0, 0, 0, tzinfo=None)

coredata_start_unix = int(mktime(coredata_start_date.timetuple()))

unix_timestamp = coredata_start_unix + coredata_timestamp


The approach is pretty straightforward, but one thing to keep in mind is to make sure you're converting between the same units. For example, I've noticed that some Core Data timestamp values are stored in nano seconds.

The example above assumes that we're converting between two timestamps that are both in seconds. If you're looking into converting a nano second based Core Data timestamp to a second based Unix timestamp make sure to divide that value by 1000000000 before the addition. While if you're looking into keeping the result in nano seconds make sure to get the starting Unix timestamp representing the Core Data base date in nano seconds too.

I hope you find this quick tip useful, happy to hear your questions or feedback in the comments!

Enjoyed this post? Help me spread the word and let me know your feedback!

Subscribe via