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)
Comments
by OzgurBatu on 2008-10-15 19:54:57
by widged on 2008-10-10 21:09:12
by Bill on 2008-10-10 18:15:34
by John Dalziel on 2008-10-10 17:41:43
by chat on 2008-10-12 17:08:18
by htmlmekani on 2008-10-12 16:42:20
by Dave on 2009-02-05 05:34:20
by Dave on 2009-02-05 05:34:55
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)
by Dave on 2009-02-05 05:35:28
by Dave on 2009-02-05 05:37:55
by Shubhadeep on 2009-06-13 07:03:37
by markvan on 2010-05-20 12:20:38
by Himanshu on 2010-06-01 10:32:36
by Caio on 2010-06-08 22:21:37
by sheshakiran on 2011-04-08 10:05:27