0

I am able to convert to date from a timestamp, but the conversion from datetime to timestamp is giving wrong answer. here's my code

import datetime
from pytz import timezone

datetime.datetime.fromtimestamp(1426017600,timezone("Asia/Dubai")).strftime('%Y-%m-%d %H:%M:%S')
output:'2015-03-11 00:00:00'

How to include timezone when converting back to timestamp from datetime ?

>>datetime.datetime(2015,03,11).strftime('%s')
output:1426012200
Rahul
  • 3,208
  • 8
  • 38
  • 68
  • Another SO answer has what you're looking for [here](http://stackoverflow.com/a/18646797/943773). Look at the second part about converting from local time to another timezone. – ryanjdillon May 28 '16 at 06:36

1 Answers1

0
from datetime import datetime, time, date
from pytz import timezone, utc

tz = timezone("Asia/Dubai")
d = datetime.fromtimestamp(1426017600,tz)
print d
midnight = tz.localize(datetime.combine(date(d.year, d.month, d.day),time(0,0)), is_dst=None)
print int((midnight - datetime(1970, 1, 1, tzinfo=utc)).total_seconds())

Based on code from python - datetime with timezone to epoch

Community
  • 1
  • 1
Serenity
  • 35,289
  • 20
  • 120
  • 115