Help with date/time functions

I want to build an app for Tidbyt that announces upcoming birthdays for the user. Can someone point me to documentation for date/time functions for Starlark language? I need to compare the current date to stored birthdates to determine upcoming dates, etc. I’m fairly new to Python, I’m an experienced programmer (JavaScript, Visual Basic, php) but I’m not sure if the date/time functions available in Starlark are the same found in the regular Python language, or perhaps a subset script? Thanks for any help!

These are all the modules available for your app to use:
https://tidbyt.dev/docs/reference/modules

In your case, you’re looking for the time module. :wink:
For some of them, you’re gonna be redirected to a Github page where you can open the doc.go file to see the documentation.

I also use this site a lot, it covers all aspects of Starlark, including the same time module:

Some basic examples:

load("time.star", "time")

# get the current time
now = time.now()

# compare the date components
if now.year == 2024 and now.month == 4 and now.day == 1:
  print("What a joke, it's April 1st 2024!")

# create a duration
one_day = time.parse_duration("24h")

# add the duration
tomorrow = now + one_day

# print a formatted string, this one is a bit tricky
# you need to use the date 2006-01-02T15:04:05Z07:00 as a reference
# to print tomorrow in the format mm/dd/yyyy hh:mm AM/PM you do:
print(tomorrow.format("01/02/2006 03:04 PM"))

Your use case seems simple as you’re just working with dates. But with more time sensitive apps you usually need to account for the user’s timezone and do some conversions. You’ll see that the time module has some functions for that, and that most functions also have a location parameter.

Thank you so much! This is perfect. Many thanks!

Can I ask you another question: how can I compare 2 dates and determine how many days are between them? For instance, if I get the current date and I compare it to a birthday from a list and I want to know if the birthdate is 30 days or less from the current date?

You need to create a time object with the current date and another one for the date you want to compare. When you subtract one from the other you’ll get a duration object. From that you can get the difference in hours and convert that to days.

load("time.star", "time")

# current time
now = time.now()

# create the time object for the birthday date
birthday = time.time(year = 2024, month = 10, day = 8)

# subtract to get the difference
diff = birthday - now

# diff.hours has the difference in hours, we need to divide by 24 to convert to days
# we're using abs() and int() to make sure we get a positive integer number
diff_days = abs(int(diff.hours / 24))

# compare
if diff_days <= 30:
    print("Birthday is 30 days or less away!")
else:
    print("Birthday is more than 30 days away")

You are a godsend- thank you so much

1 Like