1

enter image description here

I would like to convert Datetime column to Epoch / Unix timestamp.

import pandas as pd
import yfinance as yf
import numpy as np
import time
df = yf.download(tickers='^NSEI',period='1d',interval='15m')
df.reset_index(inplace=True)
df.rename(columns = {'Datetime':'time'}, inplace = True)
df['Date'] = df['time'].dt.strftime('%Y-%m-%d')
df['time'] = df['time'].dt.strftime("%Y-%m-%d %H:%M:%S") 
df
Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74
Yash
  • 55
  • 2
  • 6
  • 1
    remove the image and share text only. – balderman Oct 03 '21 at 09:16
  • @balderman i have updated code and image is for Columns reference – Yash Oct 03 '21 at 09:18
  • 1
    What is the problem? What did you try and how it failed? Where are the `import` statements ? How can we reproduce your code without it? – balderman Oct 03 '21 at 09:19
  • 2
    Does this answer your question? [Converting to unix timestamp Python](https://stackoverflow.com/questions/42491129/converting-to-unix-timestamp-python) – Shireen Oct 03 '21 at 09:23

1 Answers1

1

Use this provide function citation

def utctimestamp(ts: str, DATETIME_FORMAT: str = "%d/%m/%Y"):
    import datetime, calendar
    ts = datetime.datetime.utcnow() if ts is None else datetime.datetime.strptime(ts, DATETIME_FORMAT)
    return calendar.timegm(ts.utctimetuple())

Example code (not tested)

# Imports
import datetime, calendar

# custom function
def utctimestamp(ts: str, DATETIME_FORMAT: str = "%d/%m/%Y %H:%M:%S"):
    ts = datetime.datetime.utcnow() if ts is None else datetime.datetime.strptime(ts, DATETIME_FORMAT)
    return calendar.timegm(ts.utctimetuple())

# updated code
df = yf.download(tickers='^NSEI',period='1d',interval='15m')
df.reset_index(inplace=True)
df.rename(columns = {'Datetime':'time'}, inplace = True)
df['Date'] = df['time'].dt.strftime('%Y-%m-%d')
df['time'] = utctimestamp(df['time'].dt.strftime("%Y/%m/%d %H:%M:%S"))
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Dean Van Greunen
  • 5,060
  • 2
  • 14
  • 28
  • 1
    it works when i enter single row value but not apply for all see image 1 https://ibb.co/myPb0ks and image 2 https://ibb.co/2ckFxNC as you can see when i am calling series its not working any fix for it? – Yash Oct 03 '21 at 10:40