Skip to content

Instantly share code, notes, and snippets.

@vn-ki
Last active March 27, 2018 00:14
Show Gist options
  • Save vn-ki/a0bd705673cc17d86c344c60840fa31d to your computer and use it in GitHub Desktop.
Save vn-ki/a0bd705673cc17d86c344c60840fa31d to your computer and use it in GitHub Desktop.
Example function to initialize astropy.TimeDelta like datetime.timedelta
from astropy.time import TimeDelta
import astropy.units as u
def get_timedelta(**kwargs):
"""Creates astropy.time.TimeDelta in the format of datetime.timedelta
Parameters
----------
days : int, float
seconds : int, float
microseconds : int, float
milliseconds : int, float
minutes : int, float
hours : int, float
weeks : int, float
Returns
-------
astropy.time.TimeDelta
"""
units = [u.day, u.second, u.microsecond, u.millisecond, u.minute, u.hour, u.week]
data = [
kwargs.get('days', 0),
kwargs.get('seconds', 0),
kwargs.get('microseconds', 0),
kwargs.get('milliseconds', 0),
kwargs.get('minutes', 0),
kwargs.get('hours', 0),
kwargs.get('weeks', 0),
]
# Multiply each element of units with each element of data,
# sum it up and return a TimeDelta
return TimeDelta(sum(map(lambda x, y: x * y, units, data)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment