Thursday, September 1, 2011

python datetime, strptime, strftime: working with datetime strings

I frequently find myself wanting to convert between a datetime object and a string representation. Here is a quick code example of swapping between the two:

t=datetime.datetime.now()
astring = t.strftime("%Y-%m-%d %H:%M:%S")
new_t = datetime.datetime.strptime(astring, "%Y-%m-%d %H:%M:%S")

No comments: