0

I have time as 2016-03-07 14:42:48.901013+05:30 but this is in the form of string. I want to have it as a datetime object type , as I want to compare it with the update_ts(auto_add_now) field of django. Any help to achieve this will be highly appreciated.

I have tried using x = datetime.strptime(ts, '%Y-%m-%dT%H:%M:%S.%UTZ') but it doesn't work for me.

the_unknown_spirit
  • 2,518
  • 7
  • 34
  • 56

3 Answers3

2

You should use correct format '%Y-%m-%d %H:%M:%S.%f' and ignore timezone: ts.split('+')[0]

x= datetime.strptime(ts.split('+')[0],'%Y-%m-%d %H:%M:%S.%f')

ofcouse you should handle timezone by yourself or use default one.

Also you can use dateutil.parser.parse:
First install the python-dateutil package: pip install python-dateutil
Then:

from dateutil.parser import parse
x = parse(ts)
datetime.datetime(2016, 3, 7, 14, 42, 48, 901013, tzinfo=tzoffset(None, 19800))

Check this reference too: Convert timestamps with offset to datetime obj using strptime

Community
  • 1
  • 1
Ali Nikneshan
  • 3,500
  • 27
  • 39
1

You can do this with dateutil parser

Before Using dateutil , install it using pip install python-dateutil

from dateutil import parser

your_date_string = '2016-03-07 14:42:48.901013+05:30'

yourDate = parser.parse(your_date_string)
# yourDate -> datetime.datetime(2016, 3, 7, 14, 42, 48, 901013, tzinfo=tzoffset(None, 19800))
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
Mani
  • 933
  • 6
  • 15
0

If you want Datetime object alone ,

a = '2016-03-07 14:42:48.901013+05:30'.split('+')[0]
get_dateiobj =  datetime.strptime(a,"%Y-%m-%d %H:%M:%S.%f")

it will return upto your timezone

dateutil also the better method it seems like angularjs - momentjs .

You can parse multiple dateformat using this.

pip install python-dateutil
than you can parse different format like,

from dateutil.parser import *
now = parse("2016-03-07 14:42:48.901013+05:30")
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118