Avoid a bad date and have a good time

Written by wendinodawashaya | Published 2017/06/06
Tech Story Tags: programming | software-development | python

TLDRvia the TL;DR App

Disclaimer: This post is for datetime in programming. I absolutely have no advise for the other types of dates normal people(like the one in the picture)

“I use the term “date/time” to mean pretty much “any type of chronological information” retrieved from a Jon Skeet blog post

Ask any programmer about their experience handling dates and time and they will probably share some war stories. I recall during my first years in varsity hearing about how dates can cause headaches for developers just like pointers can in C. I had not yet experienced that by then cause i had not yet been in the software industry. I later went went for a one year internship as a developer where i faced these issues. I remember one day leaving work with my supervisor ,a senior developer at the firm very late because of a datetime bug. Worst thing was the code was already deployed on the live environment. This was not the first date/time issue had faced since joining the company but it was the worst. This prompted me to open a question thread Quora trying to get best practices from other experienced developers to avoid such issues in the future.

Datetime has always troubled scientists since the dawn of age. This is because time is complex , try understanding relativity if think i am lying.

Time as interpreted by the master of time

Dates have always been a thorn in the foot for programmers maybe because they generally suck at the other dates 🙍.

Proof of that is the Y2K bug. The Y2K bug was a computer flaw, or bug, that may have caused problems when dealing with dates beyond December 31, 1999. The flaw, faced by computer programmers and users all over the world on January 1, 2000, is also known as the “millennium bug. They are many other date bugs that were less famous.

There are many, many questions on Stack Overflow about both parsing and formatting date/time values. Most of the references here are in python but most of the issues are universal to most programming languages that deal with datetime on the web. The best way to avoid such pitfalls is by following coding best practices. The practices may differ with developers but most of them are the same.

Common issues faced with datetime are as a result of

  • Issues with time zones
  • Inconsistent date time formats/patterns
  • Different locale settings on deployment server and local development machine
  • Date arithmetic
  • Inconsistency between value being passed to database and actual type in the database
  • Datetime serialization

The most common and best way to avoid date time errors is by not shooting yourself in the foot.

By not shooting yourself in the foot i mean always reading the documentation of the framework or language you are using. Also do know your time zone. I am going to look into some issues in brief. Most of these have other blog post written that solve them.

Time zones

A time zone is a region of the globe that observes a uniform standard time for legal, commercial, and social purposes” — Wikipedia. Time zones tend to follow the boundaries of countries and their subdivisions because it is convenient for areas in close commercial or other communication to keep the same time. This causes headaches for programmers as one has to keep track of the different time zones for each user. Your application should never handle timestamps with no timezone information. For python the datatime module has two datetime object which are naive and aware. An aware object has sufficient knowledge of applicable algorithmic and political time adjustments, such as time zone to locate itself relative to other aware objects. A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects. Whether a naive object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program. Naive objects are easy to understand and to work with. For timezone aware objects set the tzinfo attribute to an instance of a subclass of the abstract [**tzinfo**](https://docs.python.org/3.4/library/datetime.html#datetime.tzinfo "datetime.tzinfo") class. The standard library does not define any timezones (at least not well). You can see full blog article here.The best way to handle this is to use other libraries like dateutil or pytz.

>>import pytz>>import datetime as dt

If you need to parse strings containing ISO 8601 formatted timestamp, you can rely on the iso8601, which returns timestamps with correct timezone information

For a Django application if support for timezone is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms. To enable timezone , set [**USE_TZ = True**](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-USE_TZ) in your settings file and set TIME_ZONE = ‘UTC’.

from django.utils import timezone

now = timezone.now()

Inconsistent date time formats/patterns

Other issues with datetimes arise because of inconsistent formats. Such errors arise from the client side. When creating date input fields for the user do not let the user assume a date format. It is advisable to use a datepicker library for the U.I. They are quite a lot of datepicker libraries out there, just pick one you would prefer to use. If you are not American i would advise you to use dd/mm/yy or yy/mm/dd ISO format cause Americans just seek attention by doing stuff differently 😒(just saying). I would advise one to use that same format across the whole platform , that is, both server side and client side.

Date and time serialization

JSON has become a rather prevalent serialization format in recent years and it is a really good format. Most primitive data types are easy to serialize with JSON . Ints and Strings are mostly easy. Dates? A nightmare. They always will be since dates are complex objects. The problem with dates in JSON and really JavaScript in general is that JavaScript doesn’t have a date literal. To represent dates in JavaScript, JSON uses a specific string format ISO 8601 to encode dates as string. The serialization part is pretty simple but the problem arises when deserializing.

To encode a date with JSON one can use the JSON serializer’s stringify() method.

var date = new Date();console.log(date); //Thu Jun 08 2017 16:25:36 GMT+0200 (South Africa Standard Time)

var json = JSON.stringify(date);console.log(json); //"2017-06-08T14:25:36.005Z"

When deserializing the date back the string representation of the date is returned.

var dateStr = JSON.parse(json);console.log(dateStr); // "2017-06-08T14:25:36.005Z"

The date however can be converted back to an JavaScript date by passing the string into a JavaScript date constructor.

var date = new Date(dateStr);console.log(date); //Thu Jun 08 2017 16:25:36 GMT+0200 (South Africa Standard Time)

I recall when i first encountered this issue after passing a JSON array with a date object from my .Net WebForm and got /Date(1245398693390)/ after my ajax call.Fortunately stackoverflow was there to the rescue.

I had to do something somewhat similar to this to solve the issue

It turned out that that funny output was actually milliseconds since epoch.

With python serializing a datetime object raises a TypeError.

>>> import json>>> import datetime>>> now = datetime.datetime.now(datetime.timezone.utc)>>> json.dumps(now)

TypeError: datetime.datetime(2017, 6, 9, 8, 27, 26, 832835, tzinfo=datetime.timezone.utc) is not JSON serializable

To solve this parse the datetime as an isoformat object since a json date is an is an ISO string.

now = datetime.datetime.now(datetime.timezone.utc).isoformat()

Conclusion

These are some of the problems junior developers face with dates when still starting out. I did not exhaust the whole list but below are some other blog posts and videos that can help you understand more about datetime.


Published by HackerNoon on 2017/06/06