Login

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

Author:
sleepycal
Posted:
April 27, 2010
Language:
Python
Version:
1.1
Tags:
datetime precision convert usec unix microsecond date time epoch
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. JSON encode ISO UTC datetime by japerk 5 years, 11 months ago
  2. JSON decode datetime by japerk 5 years, 11 months ago
  3. isoutc template filter by japerk 5 years, 11 months ago
  4. UTC DateTime field by ludo 7 years, 7 months ago
  5. Use pexpect to control manage.py syncdb or anything else by aafshar 8 years ago

Comments

Please login first before commenting.