-2

This gets me a string. How do I go back to a datetime object so I can do some date arithmetic and such?

from datetime import datetime, timezone
s = datetime.now(timezone.utc).astimezone().isoformat()

This code snippet produces a string that I am happy with, but how do I get back to datetime?

2015-11-01T07:49:35.106745-08:00
mcu
  • 3,302
  • 8
  • 38
  • 64

2 Answers2

2

This works, but it is a lot busier than I would like to see.

dt = datetime.strptime(s[:-3]+s[-2:], "%Y-%m-%dT%H:%M:%S.%f%z")
print(dt)
mcu
  • 3,302
  • 8
  • 38
  • 64
0

Don't convert the time by using isoformat() before doing date arithmetic.

Try this:

import datetime, time

d0 = datetime.datetime.now()
time.sleep(0.1)
d1 = datetime.datetime.now()

print('trip began:{}'.format(d0.isoformat()))
print('trip ended:{}'.format(d1.isoformat()))
delta = d1 - d0
print('that took {} seconds'.format(delta.total_seconds()))

The above doesn't do the right thing for timezones and daylight saving time, but your original question seemed to have that part working:

datetime.now(timezone.utc).astimezone()

Sample output:

trip began:2015-11-01T08:52:28.326764
trip ended:2015-11-01T08:52:29.331763
that took 1.004999 seconds
davejagoda
  • 2,420
  • 1
  • 20
  • 27
  • I want to have a human-readable string as a timestamp. – mcu Nov 01 '15 at 15:50
  • @coding4fun please provide example output. – davejagoda Nov 01 '15 at 15:54
  • Please see my edited post. I would like to be accurate to milliseconds at least. – mcu Nov 01 '15 at 15:58
  • The timestamps will be used from different machines. – mcu Nov 01 '15 at 16:00
  • Thanks. The purpose of this exercise is to save the timestamp to a text file or a database as a human-readable string, and I do not want to save any other data besides that. So, how do I parse the string back into `datetime`? – mcu Nov 01 '15 at 17:06