1

Silly Question, but couldn't find the proper answer. I converted my datetime object from UTC to ist using dateutils.

utc = datetime.utcnow()
UTC = tz.gettz('UTC')
indian = tz.gettz('Asia/Kolkata')
ind = utc.replace(tzinfo=UTC)
ind.astimezone(indian).replace(microsecond=0).__str__()

Output

'2019-07-30 16:32:04+05:30'

I would like to remove the +5:30 part, how do I go about doing that, except splitting the string on '+' symbol, or how do I avoid it being added in the first place.

piyush daga
  • 501
  • 4
  • 17

2 Answers2

3

You can explicitly state your format via strftime

>>> new = ind.astimezone(indian).replace(microsecond=0)
>>> new.strftime('%Y %m %d %H:%M:%S')
'2019 07 30 16:59:56'
rafaelc
  • 57,686
  • 15
  • 58
  • 82
1

You can simply strip out the timezone from the datetime object by using tzinfo=None. The string representation will still be ISO8601, but with no timezone offset part.

str(
   datetime.now(tz=tz.gettz('Asia/Kolkata')))
   .replace(microseconds=0, tzinfo=None)
)
# '2019-07-30 16:32:04'
Håken Lid
  • 22,318
  • 9
  • 52
  • 67
  • Are you sure? In any case, I've simplified my answer a bit more, by directly calling datetime.now with a specific timezone instead of using utcnow. – Håken Lid Jul 30 '19 at 12:05
  • Apologies -- I missed the fact (in your original answer) that you were using `utcnow` rather than `now`. – unutbu Jul 30 '19 at 13:03