Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve time conversion helpers #36

Merged
merged 2 commits into from
Apr 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ repos:
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
name: isort (python)
language_version: python3.10
- id: isort
name: isort (python)
language_version: python3.10
65 changes: 44 additions & 21 deletions cxotime/cxotime.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,6 @@
iers.conf.auto_download = False


def print_time_conversions():
"""Interface to entry_point script ``cxotime`` to print time conversions"""
date = None if len(sys.argv) == 1 else sys.argv[1]
date = CxoTime(date)
date.print_conversions()


def date2secs(date):
"""Fast conversion from Year Day-of-Year date(s) to CXC seconds

Expand Down Expand Up @@ -310,9 +303,9 @@ def now(cls):

now.__doc__ = Time.now.__doc__

def print_conversions(self):
def print_conversions(self, file=sys.stdout):
"""
Print a table of conversions to other formats.
Print a table of conversions to a standard set of formats.

Example::

Expand All @@ -326,33 +319,63 @@ def print_conversions(self):
decimalyear 2010.00000
iso 2010-01-01 00:00:00.000
unix 1262304000.000

:param file: file-like, optional
File-like object to write output (default=sys.stdout).
"""
from astropy.table import Table
from dateutil import tz

formats = {
"date": "s",
"cxcsec": ".3f",
"decimalyear": ".5f",
"iso": "s",
"unix": ".3f",
}
dt_utc = self.datetime.replace(tzinfo=tz.tzutc())
dt_local = dt_utc.astimezone(tz.tzlocal())

rows = []
rows.append(["local", dt_local.strftime("%Y %a %b %d %I:%M:%S %p %Z")])
rows.append(["iso_local", dt_local.isoformat()])
conversions = self.get_conversions()

# Format numerical values as strings with specified precision
for name, fmt in formats.items():
row = [name, format(getattr(self, name), fmt)]
rows.append(row)
conversions[name] = format(conversions[name], fmt)

out = Table(rows=rows, names=["format", "value"])
formats = list(conversions)
values = list(conversions.values())
out = Table([formats, values], names=["format", "value"])
out["format"].info.format = "<s"
out["value"].info.format = "<s"

# Remove the header and print
lines = out.pformat_all()[2:]
print("\n".join(lines))
print("\n".join(lines), file=file)

def get_conversions(self):
"""
Get a dict of conversions to a standard set of formats.

Example::

>>> from cxotime import CxoTime
>>> t = CxoTime('2010:001:00:00:00')
>>> t.get_conversions()
{'local': '2009 Thu Dec 31 07:00:00 PM EST',
'iso_local': '2009-12-31T19:00:00-05:00',
'date': '2010:001:00:00:00.000',
'cxcsec': 378691266.184,
'decimalyear': 2010.0,
'iso': '2010-01-01 00:00:00.000',
'unix': 1262304000.0}
"""
from datetime import timezone

out = {}

dt_local = self.datetime.replace(tzinfo=timezone.utc).astimezone(tz=None)
out["local"] = dt_local.strftime("%Y %a %b %d %I:%M:%S %p %Z")
out["iso_local"] = dt_local.isoformat()

for name in ["date", "cxcsec", "decimalyear", "iso", "unix"]:
out[name] = getattr(self, name)

return out


class TimeSecs(TimeCxcSec):
Expand Down
Empty file added cxotime/scripts/__init__.py
Empty file.
34 changes: 34 additions & 0 deletions cxotime/scripts/print_time_conversions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import sys

from cxotime import CxoTime


def main(date=None, file=sys.stdout):
"""Interface to entry_point script ``cxotime`` to print time conversions.

:param date: str, float, optional
Date for time conversion if sys.argv[1] is not provided. Mostly for testing.
:param file: file-like, optional
File-like object to write output (default=sys.stdout). Mostly for testing.
"""
if date is None:
if len(sys.argv) > 2:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No biggie, but I naively tried "cxotime --help" and "cxotime -help" and they weren't helpful as that just throws an exception ValueError: Input values did not match any of the formats where the format keyword is optional...

So I'm not sure if there is some value to supporting some kind of usage help.

print("Usage: cxotime [date]")
sys.exit(1)

if len(sys.argv) == 2:
date = sys.argv[1]

# If the input can be converted to a float then it is a CXC seconds value
try:
date = float(date)
except Exception:
pass

date = CxoTime(date)
date.print_conversions(file)


if __name__ == "__main__":
main()
37 changes: 37 additions & 0 deletions cxotime/tests/test_cxotime.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
Simple test of CxoTime. The base Time object is extremely well
tested, so this simply confirms that the add-on in CxoTime works.
"""
import io

import astropy.units as u
import numpy as np
Expand All @@ -11,6 +12,7 @@
from Chandra.Time import DateTime

from .. import CxoTime, date2secs, secs2date
from ..scripts import print_time_conversions


def test_cxotime_basic():
Expand Down Expand Up @@ -274,3 +276,38 @@ def test_secs2date(date):
val = secs2date(t_secs)
assert isinstance(val, np.ndarray)
assert val.dtype.kind == "U"


def test_get_conversions():
t = CxoTime("2010:001:00:00:00")
out = t.get_conversions()
exp = {
"local": "2009 Thu Dec 31 07:00:00 PM EST",
"iso_local": "2009-12-31T19:00:00-05:00",
"date": "2010:001:00:00:00.000",
"cxcsec": 378691266.184,
"decimalyear": 2010.0,
"iso": "2010-01-01 00:00:00.000",
"unix": 1262304000.0,
}
assert out == exp


@pytest.mark.parametrize(
"date", ["378691266.184", "2010:001", "2010-01-01 00:00:00.000"]
)
def test_print_time_conversions(date):
out = io.StringIO()
print_time_conversions.main(date, file=out)
exp = """\
local 2009 Thu Dec 31 07:00:00 PM EST
iso_local 2009-12-31T19:00:00-05:00
date 2010:001:00:00:00.000
cxcsec 378691266.184
decimalyear 2010.00000
iso 2010-01-01 00:00:00.000
unix 1262304000.000"""
out_str = out.getvalue()
# Strip all trailing whitespace on each line
out_str = "\n".join([line.rstrip() for line in out_str.splitlines()])
assert out_str == exp
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

entry_points = {
"console_scripts": [
"cxotime = cxotime.cxotime:print_time_conversions",
"cxotime = cxotime.scripts.print_time_conversions:main",
]
}

Expand All @@ -20,7 +20,7 @@
use_scm_version=True,
setup_requires=["setuptools_scm", "setuptools_scm_git_archive"],
zip_safe=False,
packages=["cxotime", "cxotime.tests"],
packages=["cxotime", "cxotime.scripts", "cxotime.tests"],
tests_require=["pytest"],
cmdclass=cmdclass,
entry_points=entry_points,
Expand Down