You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DataFrame中的日期时间列转换为自定义格式(如30th Jan 22、8:08 PM)

Solution for Date & Time Formatting in NSE Corporate Announcements CSV

Got it, let's tweak your code to get the exact date and time formats you're looking for. The main hurdles here are adding ordinal suffixes (like th, st) to dates and converting 24-hour time to a 12-hour format with AM/PM. Here's how to make it happen:

Step 1: Add a Helper Function for Ordinal Suffixes

Python's strftime doesn't have a built-in way to add ordinal suffixes (e.g., 30th, 1st), so we'll create a small function to handle that edge case:

def add_ordinal_suffix(day):
    # Handle special cases for 11,12,13 since they always use "th"
    if 11 <= day <= 13:
        return f"{day}th"
    # Map remaining days to their correct suffix
    suffix = {1: 'st', 2: 'nd', 3: 'rd'}.get(day % 10, 'th')
    return f"{day}{suffix}"

Step 2: Full Updated Code

We'll integrate the date and time formatting right after splitting the DateandTime column. Here's the complete modified code:

import requests
import pandas as pd
from datetime import datetime
from datetime import date

def add_ordinal_suffix(day):
    if 11 <= day <= 13:
        return f"{day}th"
    suffix = {1: 'st', 2: 'nd', 3: 'rd'}.get(day % 10, 'th')
    return f"{day}{suffix}"

currentd = date.today()
s = requests.Session()
headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
url = 'https://www.nseindia.com/'
step = s.get(url,headers=headers)
today = datetime.now().strftime('%d-%m-%Y')
api_url = f'https://www.nseindia.com/api/corporate-announcements?index=equities&from_date={today}&to_date={today}'
resp = s.get(api_url,headers=headers).json()
result = pd.DataFrame(resp)
result.drop(['difference', 'dt','exchdisstime','csvName','old_new','orgid','seq_id','sm_isin','bflag','symbol','sort_date'], axis = 1, inplace = True)
result.rename(columns = {'an_dt':'DateandTime', 'attchmntFile':'Source','attchmntText':'Topic','desc':'Type','smIndustry':'Sector','sm_name':'Company Name'}, inplace = True)

# Split Date and Time columns
result[['Date','Time']] = result.DateandTime.str.split(expand=True)
result.drop(['DateandTime'], axis = 1, inplace = True)

# Format Date to "30th Jan 22"
result['Date'] = result['Date'].apply(lambda x: 
    datetime.strptime(x, '%d-%m-%Y').strftime(f"{add_ordinal_suffix(datetime.strptime(x, '%d-%m-%Y').day)} %b %y")
)

# Format Time to "8:08 PM" (12-hour format without leading zero)
result['Time'] = result['Time'].apply(lambda x: 
    datetime.strptime(x, '%H:%M:%S').strftime('%I:%M %p').lstrip('0').replace(' 0', ' ')
)

# Export to CSV
result.to_csv(f"{currentd.day}-{currentd.month}-CA.csv", index=True)
print('Saved the CSV File')

Key Breakdown:

  • Date Formatting: We first parse the raw date string (in %d-%m-%Y format) into a datetime object. We then grab the day, add the correct ordinal suffix using our helper function, and combine it with the abbreviated month (%b) and 2-digit year (%y).
  • Time Formatting: We parse the 24-hour time string (in %H:%M:%S format) into a datetime object, then format it with %I:%M %p to get the 12-hour time with AM/PM. We use lstrip('0') to remove leading zeros from the hour (e.g., 08 becomes 8) and replace(' 0', ' ') to clean up any leading zeros in minutes (though %M keeps the two-digit minute, which matches your desired 8:08 PM format).

内容的提问来源于stack exchange,提问作者Jay shankarpure

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 10:47:32