Skip to content
This repository was archived by the owner on Jun 14, 2023. It is now read-only.
Open
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
2 changes: 1 addition & 1 deletion AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ Development Lead
Contributors
------------

None yet. Why not be the first?
* Tony Flury <[email protected]>
8 changes: 8 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,11 @@ History
------------------

* First release on PyPI.


0.2.0 (2016-05-22)
------------------

* Implementation of the `cui.DateTime`_ class.

.. _`cui.DateTime`: CUI/Date_Time
8 changes: 6 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,16 @@ Features

* CUI Formatting
* NHS Number (e.g. 123 456 7890)
* Dates (e.g. 01-Jan-1970 01:20)
* Dates (e.g. 01-Jan-1970 01:20) : Initial Implementation in 0.2.0
* Patient Name (e.g. BLOGGS Joe)


Credits
---------
-------

Software and documentation developed by :

Matt Stibbs and Tony Flury.

This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.

Expand Down
82 changes: 82 additions & 0 deletions docs/CUI/Date_Time.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
========================
CUI Date Time Processing
========================

The CUI defines the standard date time format as dd-mmm-YYYY HH:MM (eg. 08-Aug-1970 08:40).

The CUI date/time is a class which allows dates to be manipulated as if they were python standard library datetimes, with the addition of an easy way of inputing and outputing the datetime in the standard CUI format above.

Recognising that not every interface will produce date/times in the CUI format, it is also posible to easily create CUI standard dates/times from other input formats, such as POSIX timestamps and standard library datetime instances.

.. warning::

The current implementation of the CUI Date/time class is not fully timezone aware. This **WILL** be resolved in a upcoming update.


DateTime Class
--------------

.. py:function:: nhspy.cui.DateTime( initial=None )

The ``initial`` argument is as follows :

- ``initial`` is None : The DateTime instance is created from the current local date/time.
- ``initial`` is a number (integer, floating point or a Decimal), then this number is a POSIX timestamp (count of seconds since 01-Jan-1970 00:00. The DateTime class will accept and process fractional timestamps correctly, although the standard CUI format displays data with a resolution of 1 minute only.
- ``initial`` is a string, then it is expected to be formatted in a CUI Date format (dd-mmm-YYYY HH:MM). If the string is not formatted in the expected format, a ValueError exception will be raised.
- ``initial`` is a Python standard library datetime, the DateTime instance will represent the same date/time as the datetime instance.

Manipulating DateTime instances
-------------------------------

DateTime instances can be manipulated the same as any standard library datetime. Elements can be extracted by using the standard datetime attributes :

+-----------------+-----------------------------------------+---------------------------------+
| Attribute | Definition | Range |
+=================+=========================================+=================================+
| year | The year | From ``MINYEAR`` to ``MAXYEAR`` |
+-----------------+-----------------------------------------+---------------------------------+
| month | The month number (from 1) | From 1 to 12 inclusive |
+-----------------+-----------------------------------------+---------------------------------+
| day | The day of the month | From 1 to 31 inclusive |
+-----------------+-----------------------------------------+---------------------------------+
| hour | The hour on the 24 hour clock | From 0 to 23 inclusive |
+-----------------+-----------------------------------------+---------------------------------+
| minute | Minutes past the current hour | From 0 to 59 inclusive |
+-----------------+-----------------------------------------+---------------------------------+
| second | Seconds within the current minute | From 0 to 59 inclusive |
+-----------------+-----------------------------------------+---------------------------------+
| microsecond | microseconds with the current second | From 0 to 999999 inclusive |
+-----------------+-----------------------------------------+---------------------------------+

DateTime instances can be compared to standard library datetimes, and can have timedelta instances added and subtracted from them. In all cases they behave exactly the same as standard library datetimes. See the `Python Standard Library datetime module`_ for more details.

.. _`Python Standard Library datetime module`: https://docs.python.org/2.7/library/datetime.html

Output for CUI DateTime
-----------------------

The DateTime class is intended to work well with the standard ``.format`` output method to allow
control over the formatting of how the information is output.

A format type of `v` will always output the DateTime in the CUI DateTime format :

.. code-block:: Python

>>> from nhspy.cui import DateTime
>>> "{0:v}".format(DateTime(0)) # Create CUI Date format for 1970/01/01 00:00 (timestamp=0)
'01-Jan-1970 00:00'

With the `v` format type the full format specifier is :

``[[fill]align][width]v`` where :

- ``fill`` : A single fill character which is used when the output is aligned within a fixed width. Defaults to a space if ommitted.
- ``align`` : One of ``>`` (right align - default) ``<`` (left align) or ``^`` (centered).
- ``width`` : An integer given the the minimum text width for the output. Note the standard format is always 17 characters long.

If the ``v`` format is not used, then the following other output formats can be used :

- an empty format string (i.e. no type, alignment, width or other fill character) will generate a string containing the date in ISO format : 'YYYY-mm-dd HH:MM:SS.
- The format specifier might also contain one or more datetime part format specifiers, as would be passed to ``.strftime``. See also See the `Python Standard Library datetime module - strftime & strptime behaviour`_ for more details.

.. _`Python Standard Library datetime module - strftime & strptime behaviour`: https://docs.python.org/2.7/library/datetime.html?highlight=datetime.__format__#strftime-strptime-behavior
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@

# General information about the project.
project = u'NHSPy'
copyright = u'2016, Matt Stibbs'
copyright = u'2016, Matt Stibbs & Tony Flury'

# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
Expand Down
2 changes: 2 additions & 0 deletions docs/history.rst
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
.. include:: ../HISTORY.rst


24 changes: 23 additions & 1 deletion docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,28 @@
Usage
=====

To use NHSPy in a project::
To use NHSPy in a project

.. code-block:: Python

import nhspy


To use the CUI formats directly

.. code-block:: Python

import nhspy.cui


or

.. code-block:: Python

from nhspy import cui


For specific information on the modules and classes see

.. toctree::
CUI/Date_Time
124 changes: 124 additions & 0 deletions nhspy/cui.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
#!/usr/bin/env python
# coding=utf-8
"""
# nhspy : Implementation of cui

Summary :
Implements Common User Interface formatting for key functionality
Use Case :
As a Developer I want standard common user Interface Library So that I can develop applications which will
display data in a consistent manner

Testable Statements :
Can I input date/time information in the CUI date format (dd-mmm-YYYY HH:MM)
Can I manipulate date/time information is manner compliant with python standard libraries
Can I output date/time information in the CUI date format (dd-mmm-YYYY HH:MM)
....
"""

import re
from datetime import datetime
from numbers import Real

__author__ = 'Tony Flury : [email protected]'
__created__ = '21 May 2016'


class _Core(object):
""" _Core mixin - a place for common cui functionality
All Cui Data types must inherit from _Core
"""
fmt_spec = re.compile(
r"""
(?x) # Allow Verbose
(
(?P<fill>.?) # Optional Fill Character
(?P<align>[<>^]?) # Optional Align Character
)
(?P<width>\d*?) # Optional Width specifier
v # Format type is v
""")

def __format__(self, format_spec):
raise NotImplemented(
"All cui data types must implement their own __format__ method if their "
"other baseclass does not support it")

# noinspection PyInitNewSignature
class DateTime(datetime, _Core):
"""Date class - supports all the normal date/tme functions, and nhs cui formatting"""

def __new__(cls, initial=None):
""" Create a CUI compliant DateTime Object, from the initial value
initial : Either
numeric - a timestamps of seconds since 1970-01-01 00:00
datetime - a value derived from the datetime module
string - a text value in nhs standard format (e.g. 01-Jan-1970 01:20)
if initial is not provided - defaults to now()
"""

initial_date = None

if initial is None:
initial_date = datetime.now()

if isinstance(initial, Real):
initial_date = datetime.utcfromtimestamp(initial)

if isinstance(initial, str):
initial_date = datetime.strptime(initial, '%d-%b-%Y %H:%M')

if isinstance(initial, datetime):
initial_date = initial

if initial_date is None:
raise ValueError(
'Invalid value for initial argument - must be a numeric, string, datetime, Callable or None')

return datetime.__new__(cls, initial_date.year, initial_date.month, initial_date.day,
initial_date.hour, initial_date.minute, initial_date.second, initial_date.microsecond,
initial_date.tzinfo)

def __format__(self, format_spec):
""" Magic method to implement customised formatting"""
if not format_spec: # No format spec - always return the ISO format
return super(DateTime, self).__str__()

fmt_match = DateTime.fmt_spec.match(format_spec)
if fmt_match:
val, fmt = self.strftime('%d-%b-%Y %H:%M'), format_spec[:-1] + "s"
return "{val:{fmt}}".format(fmt=fmt, val=val)
else:
val, fmt = self, format_spec
return super(DateTime, self).__format__(fmt)

def __str__(self):
return "{me:v}".format(me=self)


class NHSNumber(str, _Core):
# noinspection PyMissingConstructor
def __init__(self, number):
""" Create a CUI compliant NHSNumber - basically a string with customised formatting

:param number: The initial number - with or without separators
"""
pass

def __format__(self, format_spec):
""" Magic method to implement customised formatting"""
pass


class Name(_Core):
def __init__(self, last_name='', first_name=''):
""" Create a CUI compliant NHSNumber - basically a string with customised formatting

:param last_name : The person's last name
:param first_name : The person's first name
"""
pass

def __format__(self, format_spec):
""" Magic method to implement customised formatting"""
pass
15 changes: 15 additions & 0 deletions nhspy/nhspy.py
Original file line number Diff line number Diff line change
@@ -1 +1,16 @@
# -*- coding: utf-8 -*-
"""
# nhspy : Implementation of nhspy

Summary :
Implements a common core of functionality for use on NHS projects
Use Case :
As a Developer I want a standard common core of functionality So that I can develop applications which behave in a
consistent manner.

Testable Statements :
Can I Input, Manipulate and Output date/times in a form that is
compliant with the CUI Date format (dd-mm-YYYY HH:MM) - See cui.py
....
"""

4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@
]

test_requirements = [
# TODO: put package test requirements here
'flake8'
]

setup(
name='nhspy',
version='0.1.0',
version='0.2.0',
description="A python package to help with NHS-specific functions.",
long_description=readme + '\n\n' + history,
author="Matt Stibbs",
Expand Down
Loading