-2

Need to get range of current month in epoch format (From start and to the end of month, two variables, epoch format with milliseconds). How to do that? Maybe someone already did this and can help?

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
  • Or: [Convert a column of datetimes to epoch in Python](https://stackoverflow.com/questions/35630098/convert-a-column-of-datetimes-to-epoch-in-python) – Brad Solomon Nov 27 '17 at 23:51

2 Answers2

3

Not pandas, but in general:

from datetime import datetime
import calendar

epoch = datetime.utcfromtimestamp(0)

def unix_time(dt):
    return (dt - epoch).total_seconds() * 1000.0


today = datetime.now()
lastDay = calendar.monthrange(today.year, today.month)[1]

firstDayOfMonth = today.replace(day=1)
lastDayofMonth = today.replace(day=lastDay)

firstEpoch = unix_time(firstDayOfMonth)
lastEpoch = unix_time(lastDayOfMonth)
Martin
  • 1,095
  • 9
  • 14
2

From the Pandas docs: From timestamp to epoch. Convert datetime to int64, then divide by conversion unit.

import pandas as pd

def to_epoch(**kwargs):
    """returns: NumPy ndarray."""
    stamps = pd.date_range(**kwargs)
    return stamps.view('int64') // pd.Timedelta(1, unit='s')

to_epoch(start='2017-04-01', end='2017-04-30')
array([1491004800, 1491091200, 1491177600, 1491264000, 1491350400,
       1491436800, 1491523200, 1491609600, 1491696000, 1491782400,
       1491868800, 1491955200, 1492041600, 1492128000, 1492214400,
       1492300800, 1492387200, 1492473600, 1492560000, 1492646400,
       1492732800, 1492819200, 1492905600, 1492992000, 1493078400,
       1493164800, 1493251200, 1493337600, 1493424000, 1493510400])
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235