Dealing with Time and time Math

I wrote most of my app in Python to get it working right with the API calls and now I need to Starlarkify my time operations. Here’s what I need to do:

get the current Unix epoch time - this seems to be time.now().
take that time and subtract 24 hours (as in yesterday). I do see a parse_duration here (time package - go.starlark.net/lib/time - Go Packages) but not sure what do to with it after.

Take some other timestamps and display them in a coherent format, perhaps from_timestamp() and then parse_time()?

Python here:

endDate = int(time.time()) * 1000   # now
startDate = endDate - DAYS_TO_GET*MS_IN_A_DAY  # N days ago


myDate = time.strftime(‘%Y-%m-%d %H:%M:%S’, time.localtime(event[“eventDate”]))

When working with the time module, it’s usually a good idea to take the device’s timezone into consideration.

# You can get the timezone by doing:
tz = config.get("$tz", "America/New_York")

# Locally $tz is None, so America/New_York will be returned instead.
# On the device, $tz will have the device's location timezone.

After that, you can do some time manipulations like this:

# Current time in user's timezone
now = time.now().in_location(tz)

# now as a UNIX timestamp
print(now.unix)

# subtract 24h from now
yesterday = now - time.parse_duration("24h")

Formatting took me some time to understand, but the key is using the components of the date Monday, January 2, 2006, 15:04:05 GMT-7 as a reference for the format() function.

# print now formatted as yyyy-mm-dd hh:mm:ss (hours in 24h format)
print(now.format("2006-01-02 15:04:05"))

# formatting the hour as 12h
print(now.format("2006-01-02 03:04:05"))

# add the short week day, AM/PM indicator and and timezone offset
print(now.format("Mon 2006-01-02 03:04:05PM -07"))

Time module documentation: starlib/time/doc.go at master · qri-io/starlib · GitHub
Original Go module documentation: time package - time - Go Packages

2 Likes

Thanks, this really got me unstuck. For anyone else following watch the double negative on the time duration.

yesterday = now + time.parse_duration(“-24h”)
or
yesterday = now - time.parse_duration(“24h”)

works correctly

Ahhh right, I had a double negative there at the example code.
Fixed it, thanks.