473,811 Members | 2,714 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

datetime.fromst r() - how?

Below is what I'm currently using to construct datatime objects from
strings. Date and time objects are made up similar. To and from string
conversions are frequently needed in SQL neighborhood.

(1) Is there reason enough to ask for a 'datetime.froms tr(...)'
method? At least to convert ISO timestamps?

(2) You've got a better/different idea? Glad to see. Don't let me die
with this open question ... ;-)

mb - Martin
import datetime,time

class mysql_date(date time.date):
"Represent and convert 'YYYY-MM-DD'-like date values."

def fromstr(Cls,s,f ='%Y-%m-%d'):
try:
return Cls(*time.strpt ime(s,f)[:3])
except:
return None
fromstr = classmethod(fro mstr)

dt = mysql_date.from str('2004-07-20')
print repr(dt)
print dt

""" should print:
mysql_date(2004 , 7, 20)
2004-07-20
"""

Jul 18 '05 #1
3 4213
Martin Bless wrote:

Below is what I'm currently using to construct datatime objects from
strings. Date and time objects are made up similar. To and from string
conversions are frequently needed in SQL neighborhood.

(1) Is there reason enough to ask for a 'datetime.froms tr(...)'
method? At least to convert ISO timestamps? Does this help?
http://www.python.org/cgi-bin/moinmoin/WorkingWithTime

(2) You've got a better/different idea? Glad to see. Don't let me die
with this open question ... ;-)

mb - Martin

import datetime,time

class mysql_date(date time.date):
"Represent and convert 'YYYY-MM-DD'-like date values."

def fromstr(Cls,s,f ='%Y-%m-%d'):
try:
return Cls(*time.strpt ime(s,f)[:3])
except:
return None
fromstr = classmethod(fro mstr)

dt = mysql_date.from str('2004-07-20')
print repr(dt)
print dt

""" should print:
mysql_date(2004 , 7, 20)
2004-07-20
"""

Jul 18 '05 #2
m.*****@gmx.de (Martin Bless) wrote in message news:<40******* ********@news.v ersatel.de>...
Below is what I'm currently using to construct datatime objects from
strings. Date and time objects are made up similar. To and from string
conversions are frequently needed in SQL neighborhood.

(1) Is there reason enough to ask for a 'datetime.froms tr(...)'
method? At least to convert ISO timestamps?

(2) You've got a better/different idea? Glad to see. Don't let me die
with this open question ... ;-)


import datetime
def strToDate(ymd):
return datetime.date(* map(int, ymd.split('-')))
Jul 18 '05 #3
Dan Bishop <> wrote in
<ad************ **************@ posting.google. com>:

import datetime
def strToDate(ymd):
return datetime.date(* map(int, ymd.split('-')))


Yes, thanks, I like your solution better. This way I don't have to use
'time' as a second module. For those interested, here's what I'm using
now.

It's a pity the 'datetime' module lacks 'time.strptime( )'
functionality. In contrast it does provide 'strftime()' methods.

mb - Martin
# date,time,datet ime,timestamp handling for MySQLdb
# independant from mxdate

class mysql_date(date time.date):
"Represent and convert 'YYYY-MM-DD'-like date values."

def fromstr(Cls,s):
try:
return Cls(*map(int,s. split('-'))[:3])
except:
return None
fromstr = classmethod(fro mstr)

class mysql_time(date time.time):
"Represent and convert 'HH:MM:SS'-like time values."

def fromstr(Cls,s):
"Construct instance from string."
try:
return Cls(*map(int,s. split(':'))[:3])
except:
return None
fromstr = classmethod(fro mstr)

class mysql_datetime( datetime.dateti me):
"Represent and convert 'YYYY-MM-DD HH:MM:SS'-like datetime
values."

def fromstr(Cls,s):
"Initialize instance from string."
try:
return Cls(*map(int,s. replace('-',' ').replace(':', '
').split())[:6])
except:
return None
fromstr = classmethod(fro mstr)

class mysql_timestamp (datetime.datet ime):
"Represent and convert 'YYYYMMDDHHMMSS '-like timestamp values."

def fromstr(Cls,s,f ='%Y%m%d%H%M%S' ):
"Initialize instance from string."
try:
return
Cls(*map(int,[s[0:4],s[4:6],s[6:8],s[8:10],s[10:12],s[12:14]]))
except:
return None
fromstr = classmethod(fro mstr)

def __str__(self):
return self.strftime(' %Y%m%d%H%M%S')

myconv = MySQLdb.convert ers.conversions .copy()
myconv.update({
FIELD_TYPE.TIME STAMP : mysql_timestamp .fromstr,
FIELD_TYPE.DATE TIME : mysql_datetime. fromstr,
FIELD_TYPE.DATE : mysql_date.from str,
FIELD_TYPE.TIME : mysql_time.from str,
})

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2531
by: Max M | last post by:
# -*- coding: latin-1 -*- """ I am currently using the datetime package, but I find that the design is oddly asymmetric. I would like to know why. Or perhaps I have misunderstood how it should be used? I can make a datetime easily enough
16
10517
by: PK9 | last post by:
I have a string variable that holds the equivalent of a DateTime value. I pulled this datetime from the database and I want to strip off the time portion before displaying to the user. I am using C# eg. - String variable "strMyDate" holds the value "1/1/2005 12:00:00 AM" from the database. - I do not care about the time portion, I only want "1/1/2005" for display.
15
14290
by: Fritz Switzer | last post by:
I'd like to have a string assigned the value of a DateTime.AddMinutes(amount) so that the string is formatted in "HH:MM" format. For example: DateTime.Now.AddMinutes(30) returns "00:30" DateTime.Now.AddMinutes(90) returns "1:30" or "01:30"
3
4240
by: Andrew S. Giles | last post by:
Hello, I am importing a flat text file, and putting it into a datagrid for display on a form. Currently the users have their dates and times seperated. I have two fields, therefore in the datatable feeding the datagrid control. Both are of the DateTime Type. How do I get the time field to display only the Time, and not the date, which is apparently the default.
6
8994
by: Ante Perkovic | last post by:
Hi, How to declare datetime object and set it to my birthday, first or last day of this month or any other date. I can't find any examples in VS.NET help! BTW, what is the difference between date and datetime classes? Please, help
5
2009
by: I am Sam | last post by:
I have created this DateTime object and instanced it I think correctly DateTime myClubNow1=new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,DateTime.Now.Hour,DateTime.Now.Minute,DateTime.Now.Second); I keep getting the below error: Object reference not set to an instance of an object. I don't know what the problem could be. Can someone help me with this? It
11
7258
by: Cor Ligthert | last post by:
Hello everybody, Jay and Herfried are telling me every time when I use CDate that using the datetime.parseexact is always the best way to do String to datetime conversions. They don't tell why only that I have to listen to them because they know it better. They told also that in a business situation it is better to use datetime.parseexact for changing cultures and not to use the globalization setting. I did not give them this sample,...
9
4934
by: Phil B | last post by:
I am having a problem with a datetime from a web services provider The provider is sending the following SOAP response <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="urn:JadeWebServices/WebServiceProvider/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
0
16514
yasirmturk
by: yasirmturk | last post by:
Standard Date and Time Functions The essential date and time functions that every SQL Server database should have to ensure that you can easily manipulate dates and times without the need for any formatting considerations at all. They are simple, easy, and brief and you should use them any time you need to incorporate any date literals or date math in your T-SQL code. create function DateOnly(@DateTime DateTime) -- Returns @DateTime...
0
9605
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10647
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10386
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10133
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7669
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6889
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5554
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4339
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3017
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.