HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Writing a utility class for converting between datetime and timestamp

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
writingutilitybetweenfortimestampandconvertingclassdatetime

Problem

I'm writing an Python application that uses frequently datetime and Unix timestamp. I know Python is 'batteries included', however, I found that converting between datetime and timestamp in Python 2.6 is not trivial. That's why I wrote this utility class. This code works as expected, for Python 2.6, 2.7, and 3.4.

I want the code style of my code reviewed. I don't know whether my function names like dttomicrotimestamp and code styles (like @staticmethod) are suitable for pythonic way of coding.

#!usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division

import time
import datetime
import pytz
from tzlocal import get_localzone

class datetimeutil:
    @staticmethod
    def strtodt(text):
        try:
            dt = datetime.datetime.strptime(text, "%Y-%m-%d %H:%M:%S.%f")
        except:
            dt = datetime.datetime.strptime(text, "%Y-%m-%d %H:%M:%S")
        return get_localzone().localize(dt)

    @staticmethod
    def dttotimestamp(dt):
        if dt.tzinfo is None:
            dt = get_localzone().localize(dt)
        return datetimeutil._totalseconds(
            (dt - dt.utcoffset()).replace(tzinfo=None) -
            datetime.datetime(1970, 1, 1))

    @staticmethod
    def dttomicrotimestamp(dt):
        return int(datetimeutil.dttotimestamp(dt) * 1e6)

    @staticmethod
    def timestamptodt(timestamp):
        return get_localzone().localize(datetime.datetime.fromtimestamp(timestamp))

    @staticmethod
    def microtimestamptodt(microtimestamp):
        return datetimeutil.timestamptodt(microtimestamp / 1e6)

    @staticmethod
    def _totalseconds(timedelta):
        return ((timedelta.seconds + timedelta.days * 24 * 3600) * 1e6 
                + timedelta.microseconds) / 1e6

Solution

Let's examine the code:

#!usr/bin/python


you don't need to execute the code directly, so why this line?

class datetimeutil:
    @staticmethod


why a class with static methods? Keep it simple, write global functions. You already have the module which encapsulates the functions.

def strtodt(text):


I don't like too much the names of these functions. I know that also python uses ugly names (words without any separator) but I think you could improve this... for example: str_to_dt or str2dt seem better to me.

About the functionality. Managing dates is a quite difficult task. The python library in my opinion makes a great job in distinguishing naive and aware datetimes. Your wrapper module simplifies this by considering each naive datetime as a localtime (if I understand it correctly). I think it is not good to hide this decision in your code. Explicit is better, even if it could me more verbose.

Also I think you missed the timedelta.total_seconds function, which could be used in your code.

Code Snippets

#!usr/bin/python
class datetimeutil:
    @staticmethod
def strtodt(text):

Context

StackExchange Code Review Q#98965, answer score: 2

Revisions (0)

No revisions yet.