0

I am facing a very strange problem. I have UTC timestamp of one of the days of the month, and I need to find UTC timestamp of beginning of the month and end of month.

For example, if timestamp = 1435791600 for 07 Jan 2015 11 PM I need timestamp one 01 Jan 2015 12 AM and 31 Jan 11:59 PM.

Issue is when I use datetime to calculate first and last day of the month, and then try to retrieve timestamps from new values, the timestamps are being returned in local time instead.

This is my code:

gb_timestamp = 1441065600000
print '------'
timestamp = datetime.datetime.utcfromtimestamp(gb_timestamp/1000.0)
print timestamp
print int(timestamp.strftime("%s")) * 1000
tsMonthStart =  timestamp.replace(day=1).replace(hour=0).replace(minute=0).replace(second=0).replace(microsecond=0)
tsMonthEnd = timestamp.replace(hour=23).replace(minute=59).replace(second=59).replace(microsecond=999999)
mlist = [1,3,5,7,8,10,12]
if tsMonthEnd.month in mlist:
    tsMonthEnd = tsMonthEnd.replace(day=31)
elif (tsMonthEnd.month == 2) and (tsMonthEnd.year%4 !=0):
    tsMonthEnd = tsMonthEnd.replace(day=28)
elif (tsMonthEnd.month == 2) and (tsMonthEnd.year%4 ==0):
    tsMonthEnd = tsMonthEnd.replace(day=29)
else:
    tsMonthEnd = tsMonthEnd.replace(day=30)
print tsMonthStart
print tsMonthEnd

The very first print statement changes time to 1441080000000. Output:

----------------
1441080000000

Can someone please help. How should I resolve this. Thanks in advance.

Turn
  • 6,656
  • 32
  • 41
Shilpi
  • 5
  • 3
  • Can you clean up the code in your question? The formatting doc here should help: http://stackoverflow.com/help/formatting – Turn Dec 12 '15 at 02:33
  • unrelated: use `calendar.monthrange()` to find the last day of the month. Use `utc_time = datetime(1970, 1, 1) + timedelta(milliseconds=1441065600000)` (assuming the input is POSIX timestamp) instead of `utcfromtimestamp()`, to extend the range on some platforms and to avoid losing precision on floating-point arithmetics. – jfs Dec 12 '15 at 11:42

1 Answers1

2

That's not how you convert datetimes back to unix timestamps. Use something like this:

    def datetime_to_timestamp(dt):
       return (dt - datetime.datetime(1970, 1, 1)).total_seconds()

The answer here explains why strftime('%s') isn't valid for datetime objects.

Community
  • 1
  • 1
Turn
  • 6,656
  • 32
  • 41