Going from a datetime object to a string in Python:
The datetime to string, easy; string to datetime… oh my, my! article by Aral Balkan, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial 2.0 UK: England License.
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)
The datetime to string, easy; string to datetime… oh my, my! article by Aral Balkan, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial 2.0 UK: England License.
Nice Regex! Makes the code so much shorter than doing it the long way.
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.
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”);
thanks aral. l want to ask a question. oyur page rank 6 now. why. :(
thank you admin
it realy works. Thank you…
There’s a cheaper (as in “cheap-n-nasty”), more easily extensible method
The following code converts a timestamp or date string to a date object and prints it out (I needed to be able to do this for an arb reason):
#begin code
import datetime
import sys
import os
# much fudgery
def utctime(dt):
return (((dt.toordinal()-719163)*24+dt.hour)*60+dt.minute)*60+dt.second
def try_formats():
ret = []
ret.append(”%Y-%m-%d”)
ret.append(”%Y/%m/%d”)
ret.append(”%d/%m/%Y”)
ret.append(”%d-%m-%Y”)
ret.append(”%d/%m/%y”)
ret.append(”%d-%m-%y”)
ret.append(”%Y-%m-%d %H:%M:%S”)
ret.append(”%d-%m-%Y %H:%M:%S”)
ret.append(”%Y/%m/%d %H:%M:%S”)
ret.append(”%d/%m/%Y %H:%M:%S”)
ret.append(”%d-%m-%y %H:%M:%S”)
ret.append(”%y/%m/%d %H:%M:%S”)
ret.append(”%d/%m/%y %H:%M:%S”)
ret.append(”%Y-%m-%d %H:%M”)
ret.append(”%d-%m-%Y %H:%M”)
ret.append(”%Y/%m/%d %H:%M”)
ret.append(”%d/%m/%Y %H:%M”)
ret.append(”%d-%m-%y %H:%M”)
ret.append(”%y/%m/%d %H:%M”)
ret.append(”%d/%m/%y %H:%M”)
return ret
def show_date(s):
FORMAT=”%Y-%m-%d %H:%M:%S”
try:
secs = int(s)
d = datetime.datetime.fromtimestamp(secs)
print(str(secs) + ” :: ” + d.strftime(FORMAT))
return
except:
pass
for f in try_formats():
try:
d = datetime.datetime.strptime(s, f)
secs = utctime(d)
print(str(secs) + ” :: ” + d.strftime(FORMAT))
return
except:
pass
print(”Unable to grok datetime / int string ‘” + s + “‘”)
def usage():
print(os.path.basename(sys.argv[0]) + ” …”)
print(” attempts to grok the date from the string you provided and”)
print(” prints out a timestamp and date string for all arguments”)
if __name__ == “__main__”:
if len(sys.argv) == 1:
usage()
else:
for arg in sys.argv[1:]:
if (arg == “–help”) or (arg == “-h”):
usage()
else:
show_date(arg)
#end code
Hope it helps someone.
import datetime
import sys
import os
# much fudgery
def utctime(dt):
return (((dt.toordinal()-719163)*24+dt.hour)*60+dt.minute)*60+dt.second
def try_formats():
ret = []
ret.append(”%Y-%m-%d”)
ret.append(”%Y/%m/%d”)
ret.append(”%d/%m/%Y”)
ret.append(”%d-%m-%Y”)
ret.append(”%d/%m/%y”)
ret.append(”%d-%m-%y”)
ret.append(”%Y-%m-%d %H:%M:%S”)
ret.append(”%d-%m-%Y %H:%M:%S”)
ret.append(”%Y/%m/%d %H:%M:%S”)
ret.append(”%d/%m/%Y %H:%M:%S”)
ret.append(”%d-%m-%y %H:%M:%S”)
ret.append(”%y/%m/%d %H:%M:%S”)
ret.append(”%d/%m/%y %H:%M:%S”)
ret.append(”%Y-%m-%d %H:%M”)
ret.append(”%d-%m-%Y %H:%M”)
ret.append(”%Y/%m/%d %H:%M”)
ret.append(”%d/%m/%Y %H:%M”)
ret.append(”%d-%m-%y %H:%M”)
ret.append(”%y/%m/%d %H:%M”)
ret.append(”%d/%m/%y %H:%M”)
return ret
def show_date(s):
FORMAT=”%Y-%m-%d %H:%M:%S”
try:
secs = int(s)
d = datetime.datetime.fromtimestamp(secs)
print(str(secs) + ” :: ” + d.strftime(FORMAT))
return
except:
pass
for f in try_formats():
try:
d = datetime.datetime.strptime(s, f)
secs = utctime(d)
print(str(secs) + ” :: ” + d.strftime(FORMAT))
return
except:
pass
print(”Unable to grok datetime / int string ‘” + s + “‘”)
def usage():
print(os.path.basename(sys.argv[0]) + ” …”)
print(” attempts to grok the date from the string you provided and”)
print(” prints out a timestamp and date string for all arguments”)
if __name__ == “__main__”:
if len(sys.argv) == 1:
usage()
else:
for arg in sys.argv[1:]:
if (arg == “–help”) or (arg == “-h”):
usage()
else:
show_date(arg)
import datetime
import sys
import os
# much fudgery
def utctime(dt):
return (((dt.toordinal()-719163)*24+dt.hour)*60+dt.minute)*60+dt.second
def try_formats():
ret = []
ret.append("%Y-%m-%d")
ret.append("%Y/%m/%d")
ret.append("%d/%m/%Y")
ret.append("%d-%m-%Y")
ret.append("%d/%m/%y")
ret.append("%d-%m-%y")
ret.append("%Y-%m-%d %H:%M:%S")
ret.append("%d-%m-%Y %H:%M:%S")
ret.append("%Y/%m/%d %H:%M:%S")
ret.append("%d/%m/%Y %H:%M:%S")
ret.append("%d-%m-%y %H:%M:%S")
ret.append("%y/%m/%d %H:%M:%S")
ret.append("%d/%m/%y %H:%M:%S")
ret.append("%Y-%m-%d %H:%M")
ret.append("%d-%m-%Y %H:%M")
ret.append("%Y/%m/%d %H:%M")
ret.append("%d/%m/%Y %H:%M")
ret.append("%d-%m-%y %H:%M")
ret.append("%y/%m/%d %H:%M")
ret.append("%d/%m/%y %H:%M")
return ret
def show_date(s):
FORMAT="%Y-%m-%d %H:%M:%S"
try:
secs = int(s)
d = datetime.datetime.fromtimestamp(secs)
print(str(secs) + " :: " + d.strftime(FORMAT))
return
except:
pass
for f in try_formats():
try:
d = datetime.datetime.strptime(s, f)
secs = utctime(d)
print(str(secs) + " :: " + d.strftime(FORMAT))
return
except:
pass
print("Unable to grok datetime / int string '" + s + "'")
def usage():
print(os.path.basename(sys.argv[0]) + " ...")
print(" attempts to grok the date from the string you provided and")
print(" prints out a timestamp and date string for all arguments")
if __name__ == "__main__":
if len(sys.argv) == 1:
usage()
else:
for arg in sys.argv[1:]:
if (arg == "--help") or (arg == "-h"):
usage()
else:
show_date(arg)
sorry, tried 3 times to post with indenting — as we all know, in python, whitespace counts!
If you can’t determine the proper indentation and you actually want the code, let me know by email:
davydm _AT_ gmail _DOT_ com
Sorry for the comment spam!
Thanks Man!
You saved me a lot of time
Thanks again
Datatype conversion heaven, this just made sense and worked.
I remember your skill from the Flash5 days and Flashkit, good to know you are still caring and sharing.
I came across this:
http://mail.python.org/pipermail/tutor/2006-March/045729.html
Code at this like has one error though, in last line instead of mytime it should be timestring
You can also use datetime.strptime(”date”,”format”) to convert string to datetime.
Note that the datetime.strptime returns a datetime object, if you want a datetime.date object you should call datetime.strptime(”date”,”format”).date().
I think it’s simpler.
Regards!