4

Possible Duplicate:
Fetching datetime from float and vice versa in python

Like many people I switched from Matlab to Python. Matlab represents each date as a number. (Integers being days since 00-00-0000, and fractions being time in the day). I believe that python does the same except off a different start date 0-0-0001

I have been playing around with datetime, but cant seem to get away from datetime objects and timedeltas. I am sure this is dead simple, but how do I work with plain old numbers (floats)?

perhaps as a bit of context:

i bring in a date and time stamp and concatenate them to make one time value:

from datetime import datetime
date_object1 = datetime.strptime(date[1][0] + ' ' + date[1][1], '%Y-%m-%d %H:%M:%S')
date_object2 = datetime.strptime(date[2][0] + ' ' + date[2][1], '%Y-%m-%d %H:%M:%S')
Community
  • 1
  • 1
reabow
  • 219
  • 1
  • 6
  • 18
  • I guess it depends on what kind of date operations you want to do. If you're used to doing mathematical operations, then that kind of thing doesn't really work well with dates.. there's so many variables which proper date objects will handle for you, so maybe it's worth thinking that through first. Just a thought! – danp Jan 05 '13 at 11:40
  • thanks NPE. That is similar, except i want to go the other way (datetime to float) – reabow Jan 05 '13 at 11:42
  • danp, maybe that is the way to go. I was looking at moving this into javascript so that I can play around with d3.js on it. but maybe I am too stuck in old Matlab ways – reabow Jan 05 '13 at 11:46
  • related: [Converting datetime.date to UTC timestamp in Python](http://stackoverflow.com/a/8778548/4279) – jfs Jan 05 '13 at 12:09

2 Answers2

8

Try this out:

import time
from datetime import datetime

t = datetime.now()
t1 = t.timetuple()

print time.mktime(t1)

It prints out a decimal representation of your date.

ATOzTOA
  • 34,814
  • 22
  • 96
  • 117
2

The datetime class provides two methods, datetime.timestamp() that gives you a float and datetime.fromtimestamp(timestamp) that does the reverse conversion. To get the timestamp corresponding to the current time you have the time.time() function.

Note that POSIX epoch is 1970-01-01.

kmkaplan
  • 18,655
  • 4
  • 51
  • 65