Login

datetime.time/datetime.datetime to Unix Epoch (with microsecond support)

Author:
sleepycal
Posted:
April 27, 2010
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

This is useful when you need to convert a datetime.datetime.now() or datetime.date.today() into a unix epoch seconds, with microsecond precision (precision only applies to datetime.datetime, as datetime.date won't have any microseconds).

I have found this is necessary for when storing the DateTime in the models as a FloatField, in order to keep the usec/microsecond precision.

At some point, I will probably create a custom model field called DateTimeWithUSec or something like that, but for now, this will do :)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def GetCurrentMicroSeconds(dt=None):
    # Ensure the type matches
    if not dt:
        dt = datetime.datetime.now()

    elif type(dt) == type(datetime.datetime.now()):
        return time.mktime(dt.timetuple())+float("0.%s"%dt.microsecond)

    elif type(dt) == type(datetime.date.today()):
        return time.mktime(dt.timetuple())

    else:
        raise ValueError, "You may only use a datetime.datetime or datetime.date instance with GetCurrentMicroSeconds"

"""
Basic Usage
"""
import datetime

# create two example dates
t = datetime.date.today()
ts = datetime.datetime.now()

# returns something like 1272322800.0
GetCurrentMicroSeconds(t)

# returns something like 1272366481.381309
GetCurrentMicroSeconds(ts)

"""
Example Django Usage:
"""
class TestObject:
    date_created = models.FloatField(default=time.time, editable=False, blank=False, null=False)

# Determine the current day, month and year.
today = datetime.date.today()
# Determine first day of month
first_day = datetime.date(today.year, today.month, 1)
# Determine last day of month
last_day = last_day_of_month(today.year, today.month)
result = TestObject.objects.filter(
            date_created__gte = GetCurrentMicroSeconds(first_day),
            date_created__lte = GetCurrentMicroSeconds(last_day)
        )

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.