简体   繁体   中英

How to show date value in another format (python date to text) on worksheet

I am using the Google Sheets API for inserting some data on my sheet. Every row has a date cell that has values in this format "2017-02-01 19:33:56+00:00" I would like it to display it in this format (02 January 2017) but I would like to have the original format hidden on the same cell.

Is there a script or something that I can use to display the date in that format?

Just add a custom numberformat from the format menu. This one should do the trick "dd MMM yyyy". The date doesn't change so if you want to go back to the old one you always can. You can use a script to switch between them using range.setNumberFormat

You can use this script to setNumberFormats():

SpreadsheetApp.getActiveRange().setNumberFormat("dd MMM yyyy");

I not familiar with the ss+00:00 not sure what that means. But perhaps you can checked the documentation below. You might be able to use range.getNumberFormat() to get and save that format for future use.

var formatString=SpreadsheetApp.getActiveRange().getNumberFormat();

This format "2017-02-01 19:33:56+00:00" is not being recognized for Google Sheets, it's because it has an additional value to the final that indicates the timezone of the date "+00:00" , i decided to create an small script for getting ride of that timezone value and also add/sub hours and minutes to the date so i can see the correct hour in my timezone.

from datetime import datetime, timedelta

def formatDatetime(o_date, f_hours=0, f_minutes=0):
    # ----- Removing the timezone from the data str
    date_a = o_date.split('+')
    date = date_a[0]
    #----------------------------------------------------
    # ----- Format/Add/Sub Hours and minutes
    date = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
    date = date + timedelta(hours=f_hours)
    date = date + timedelta(minutes=f_minutes)
    date_f = format(date, '%m/%d/%Y %H:%M:%S')
    # -------------------
    return date_f

Now google sheet recognizes this value as a date, so i can make a custom formatting for showing a nice date in my worksheet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM