Converting from Date-Time to GPS time

2.2k Views Asked by At

I want to convert an array of date-time strings (YYYY-MM-DD hh:mm:ss) to GPS seconds (seconds after 2000-01-01 12:00:00) in the python environment.

In order to get the GPS seconds for a single date in Linux BASH, I simply input date2sec datetimestring and it returns a number.

I could do this within a for-loop within python. But, how would I incorporate this within the python script, as it is an external script?

Or, is there another way to convert an array of date-time strings (or single date-time strings incorporated into a for-loop) to GPS time without using date2sec?

2

There are 2 best solutions below

2
hiranyajaya On

Updated Answer: uses Astropy library:

from astropy.time import Time

t = Time('2019-12-03 23:55:32', format='iso', scale='utc')
print(t.gps)

Here you are setting the date in UTC and t.gps converts the datetime to GPS seconds.

Further research showed that directly using datetime objects doesn't take leap seconds into account.

other helpful links here: How to get current date and time from GPS unsegment time in python

1
GeodeticCuriosity On

Here is the solution that I used for an entire array of date-times in a for-loop:

import numpy as _np
J2000 = _np.datetime64('2000-01-01 12:00:00')                    # Time origin
dateTime = [...]                                                 # an array of date-times in 'YYYY-MM-DD hh:mm:ss' format
GPSarray_secs = []                                               # Create new empty array
for i in range(0,len(dateTime)) :                                # For-loop conversion
     GPSseconds = (_np.datetime64(dateTime) - J2000).astype(int) # Calculate GPS seconds
     GPSarray_secs = _np.append(GPSarray_secs , GPSseconds)      # Append array

The simple conversion for one date-time entry is:

import numpy as _np
J2000 = _np.datetime64('2000-01-01 12:00:00')                    # Time origin
GPSseconds = (_np.datetime64(dateTime) - J2000).astype(int)      # Conversion where dateTime is in 'YYYY-MM-DD hh:mm:ss' format

Importing datetime should not be required.