In 2008, over one thousand people experienced the world’s first virtual web conference. Together, we created a new type of conference that is environmentally-friendly, affordable, and interactive.

In 2009, we are going to take it one step further.


Datetime to string, easy; string to datetime… oh my, my!

Going from a datetime object to a string in Python:

import datetime
str(datetime.datetime.now())

>>> '2008-10-10 16:40:25.126049'

String to datetime: datetime.datetime.from_string('2008-10-10 16:40:25.126049')?

Nope, you need a bit more code courtesy of Kelly Yancey (or a C extension, which you cannot use on Google App Engine):

import re
from datetime import datetime
 
def parseDateTime(s):
	"""Create datetime object representing date/time
	   expressed in a string
 
	Takes a string in the format produced by calling str()
	on a python datetime object and returns a datetime
	instance that would produce that string.
 
	Acceptable formats are: "YYYY-MM-DD HH:MM:SS.ssssss+HH:MM",
							"YYYY-MM-DD HH:MM:SS.ssssss",
							"YYYY-MM-DD HH:MM:SS+HH:MM",
							"YYYY-MM-DD HH:MM:SS"
	Where ssssss represents fractional seconds.	 The timezone
	is optional and may be either positive or negative
	hours/minutes east of UTC.
	"""
	if s is None:
		return None
	# Split string in the form 2007-06-18 19:39:25.3300-07:00
	# into its constituent date/time, microseconds, and
	# timezone fields where microseconds and timezone are
	# optional.
	m = re.match(r'(.*?)(?:\.(\d+))?(([-+]\d{1,2}):(\d{2}))?$',
				 str(s))
	datestr, fractional, tzname, tzhour, tzmin = m.groups()
 
	# Create tzinfo object representing the timezone
	# expressed in the input string.  The names we give
	# for the timezones are lame: they are just the offset
	# from UTC (as it appeared in the input string).  We
	# handle UTC specially since it is a very common case
	# and we know its name.
	if tzname is None:
		tz = None
	else:
		tzhour, tzmin = int(tzhour), int(tzmin)
		if tzhour == tzmin == 0:
			tzname = 'UTC'
		tz = FixedOffset(timedelta(hours=tzhour,
								   minutes=tzmin), tzname)
 
	# Convert the date/time field into a python datetime
	# object.
	x = datetime.strptime(datestr, "%Y-%m-%d %H:%M:%S")
 
	# Convert the fractional second portion into a count
	# of microseconds.
	if fractional is None:
		fractional = '0'
	fracpower = 6 - len(fractional)
	fractional = float(fractional) * (10 ** fracpower)
 
	# Return updated datetime object with microseconds and
	# timezone information.
	return x.replace(microsecond=int(fractional), tzinfo=tz)
 

Post Metadata

Date
October 10th, 2008

Author
Aral

Category

Tags


6 Comments

  1. Nice Regex! Makes the code so much shorter than doing it the long way.


  2. What about datetime.datetime.strptime(time_string, ‘%Y-%m-%d %H:%M:%S’)?
    My date strings from client ignore sub-second but the format could be adjusted.


  3. Could DateUtil be of help (as3 corelib, com.adobe.utils.DateUtil). For string to date conversion, they zhave parseRFC822, parseW3CDTF

    A quick Actionscript 3 workaround for MS SQL Server default date-time parsing

    When using Flex, the DateField control has a stringToDate method.

    var dob:Date = DateField.stringToDate(”06/30/2005″, “MM/DD/YYYY”);


  4. thanks aral. l want to ask a question. oyur page rank 6 now. why. :(



  5. it realy works. Thank you…


Leave a Reply