Python forum for Python programmers

Maybe useful : datetime conversion

May 20, 2011 6:27 pm
Stef Mientki

This is a multi-part message in MIME format.
--------------010304010205020303040102
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit

hello,

using datetimes from a lot of different sources,
in many languages,
I had about 30 python helper routines,
which I now packed in one class,
much simpler.
Although I used the Delphi date-format as the base,
it shouldn't be difficult to rewrite the class for another type.

The input can be one of the following types :
- None : the current date-time is used
- 30000.9 : a Delphi datetime
- 30000 : a Delphi datetime
- "30000.9" : a Delphi datetime as a string
- "30000,9" : a Delphi datetime as a (Dutch) string
- "20-5-11" : short year notation
- "20-05-2011" : long year notation
- "2009-09-24 10:12:24" : Access string
- datetime.datetime ( 2011, 1, 15 )
- time.struct_time
- wx.DateTime
- time.time() (through method from_time)

Maybe someone can use it.

cheers,
Stef



--------------010304010205020303040102
Content-Type: text/x-python;
name="module1.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
filename="module1.py"

import time
import datetime
import wx

Delphi_Date_0 = datetime.date ( *time.strptime ( '30-12-1899', '%d-%m-%Y' )[0:3]).toordinal()

# ************************************************************************
# ************************************************************************
class Delphi_Date ( float ) :
def __new__ ( self, Something = None ) :
"""
Class meant to handle any datetime type, and converts it basically to
a Delphi DateTime (float: number of days since 1-1-1900).

The input can be one of the following types :
- None : the current date-time is used
- 30000.9 : a Delphi datetime
- 30000 : a Delphi datetime
- "30000.9" : a Delphi datetime as a string
- "30000,9" : a Delphi datetime as a (Dutch) string
- "20-5-11" : short year notation
- "20-05-2011" : long year notation
- "2009-09-24 10:12:24" : Access string
- datetime.datetime ( 2011, 1, 15 )
- time.struct_time
- wx.DateTime

with extra methods, also the following can be used
- from_time : time.time float

The following output methods are available
- to_time ()
- to_datetime ()
- to_String ( self , Format = "%d-%m-%Y" )
- to_String_Short ()
- to_String_Date_Time_Short ()
- to_String_Time_Short ()
- to_String_Date_Time ()
- to_wxTime ()
- to_Iso ()
"""

# The current date-time is used, if no parameter is specified
if Something is None :
Something = datetime.datetime.now ()

# floating point is assumed to be a Delphi datetime
# to specify a time.time float, use the method from_time
# Delphi_Date().from_time ( time.time()
# which is equivalent to
# Delphi_Date()
if isinstance ( Something, float ) :
Value = Something

# sometimes a Delphi datetime is stored as an integer
elif isinstance ( Something, int ) :
Value = Something

# A string can represent a lot of things
elif isinstance ( Something, basestring ) :

# a float or integer,
# also the Ducth notation where deceimal separator is a comma
try :
Value = float ( Something.replace(',','.') )
except :

# a string as a short year notation
try :
Value = datetime.datetime.strptime ( Something, '%d-%m-%y' )
except ValueError :

# a string as a long year notation
try:
Value = datetime.datetime.strptime ( Something, '%d-%m-%Y' )
except :

# a string as a (Dutch) Access notation
try :
# Access string : "2009-09-24 00:00:00"
Value = datetime.datetime.strptime ( Something.split(' ')[0], "%Y-%m-%d" )
except :
Value = Delphi_Date_0
import traceback
traceback.print_exc

Value = Value.toordinal() - Delphi_Date_0

# datetime.datetime ()
elif isinstance ( Something, datetime.datetime ) :
Value = Something.toordinal() - Delphi_Date_0

# time.struct_time
elif isinstance ( Something, time.struct_time ) :
Value = time.mktime ( Something )
DT = datetime.datetime.fromtimestamp ( Value )
Value = DT.toordinal() - Delphi_Date_0

# wx.DateTime
elif isinstance ( Something, wx.DateTime ) :
DT = datetime.date ( Something.GetYear (),
Something.GetMonth () + 1,
Something.GetDay () )
Value = DT.toordinal() - Delphi_Date_0

else :
print type(Something), Something
raise error ( 'aap' )

return float.__new__ ( self, Value )

def from_time ( self, Time ) :
DT = datetime.datetime.fromtimestamp ( Time )
return Delphi_Date ( DT )


def to_time ( self ):
return time.mktime ( self.to_datetime().timetuple() )

def to_datetime ( self ) :
#return datetime.datetime.fromordinal ( int ( round ( self + Delphi_Date_0 )))
return datetime.datetime.fromordinal ( self + Delphi_Date_0 )

def to_String ( self , Format = "%d-%m-%Y" ) :
DT = self.to_datetime()
try :
return DT.strftime ( Format )
except :
return '01-01-1900'

def to_String_Short ( self ) :
DT = self.to_datetime()
return DT.strftime ( "%d-%m-%y" )

def to_String_Date_Time_Short ( self ) :
return self.to_String ( "%d-%m-%Y %H:%M" )

def to_String_Time_Short ( self ) :
return self.to_String ( "%H:%M" )

def to_String_Date_Time ( self ) :
return self.to_String ( "%d-%m-%Y %H:%M:%S" )

def to_wxTime( self ) :
DT = self.to_datetime()
WX = wx.DateTime()
WX.Set ( DT.day, DT.month-1, DT.year )
return WX

def to_Iso ( self ) :
"""
Transforms a Delphi Datetime into an ISO tuple: ( year, week, day-of-week )
"""
return self.to_datetime().isocalendar ()
# ************************************************************************

--------------010304010205020303040102--



Previous Thread: TK program problem
Next Thread: Python 2.6.7 release candidate 2 now available

Related Forum Topics
Datetime.datetime and mysql different after python2.3
I'm grabbing two fields from a MySQLdb connection.
One is a date type, and one is a time type.

So I put the values in two variables and print them:

import datetime
date, time = get_fields() # for example
print str(type(date)), str((type(time)))
print str(date + time)

In python 2.3.4,...
PyOpenSSL -> m2crypto conversion?
Hi,

gajim (http://gajim.org, Jabber/XMPP instatnt messenger written in
PyGtk) uses for crypto mix of some functions from the standard library,
pyOpenSSL for SSL communication, and python-crypto for E2E (encryption
of the messages ... uses RSA and AES; see...
Conversion of List of Tuples
Dear Group,

I have a tuple of list as,

tup_list=[(1,2), (3,4)]
Now if I want to covert as a simple list,

list=[1,2,3,4]

how may I do that?

If any one can kindly suggest? Googling didn't help much.

Regards,
Subhabrata.


XSLT to Python script conversion?
Hi,

I am getting more and more discouraged from using XSLT for a
transformation from one XML scheme to another one. Does anybody could
share any experience with porting moderately complicated XSLT stylesheet
(https://gitorious.org/sword/czekms-csp_bible/blobs/master/CEP2OSIS.xsl)
into...
Automatic Type Conversion to String
I'm creating a class to encapsulate OS paths, to reduce the visual
noise and typing from the os.path methods. I've got the class and nose
tests below, and everything works except the last test which I've
prefixed with XXX:

def XXXtest_should_work(self):
"""
Produces:
...
Sub-classing datetime
I'm just making the transition from 2 to 3 for one module.

With Python 2.7, I had the benefit of mx datetime, but this is not yet
available for Python 3.2.

I find that the 3.2 datetime is not subclassable, for reasons that were
known some years back.

It would help if there was a note...
Datetime module and timezone
In the datetime module, it has support for a notion of timezone but is
it possible to use one of the available timezone (I am on Linux). Linux
has a notion of timezone (in my distribution, they are stored
in /usr/share/zoneinfo). I would like to be able 1) to know the current
timezone and 2)...
PyWarts: time, datetime, and calendar modules
The interface for these modules is not intuitive. Instead of creating
true OOP objects we have lists and strings. Any calendar object should
expose string names of both: days of the week and months of the year.
It seems one (or possibly more) of the three expose this important
info however i...
Python, django datetime to string conversation helper
Online tool allows to select datetime to string format directives
quickly and to check result.


Obnoxious postings from Google Groups (was: datetime issue)
Νικόλαος Κούρας <nikos.gr33k@gmail.com> writes:

> Iam sorry i didnt do that on purpose and i dont know how this is done.
>
> Iam positng via google groups using chrome, thats all i know.

It is becoming quite clear that some change has happened recently to
Google Groups that...