0

I want to write a function that takes in a string representing timestamp, then change the year, month and day of that timestamp but not the actual time. Then I want to return the resulting timestamp as a string. I'm having some trouble with the conversion, since I think I need to convert in the following sequence: string -> timestamp -> date -> timestamp -> string. I've read through the datetime library, but I'm having some trouble with this conversion. Any assistance, would be much appreciated!

Function inputs would look like this:

def change_date(string: timestamp, string: new_date)
    #timestamp: string formatted like 1601403951777
    #new_date: string formatted like YYYY-MM-DD 

For instance timestamp 1601403951777 is Tuesday, September 29, 2020.

ENV
  • 877
  • 2
  • 10
  • 32
  • Does this answer your question? [Converting unix timestamp string to readable date](https://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date) – FObersteiner Jun 10 '21 at 05:36

2 Answers2

0

Try this,

from datetime import datetime
def change_date(dt):
    #timestamp: string
    #new_date: string formatted like YYYY-MM-DD
    d= datetime.fromisoformat(dt)
    new_date = d.strftime(('%Y-%m-%d'))
    print(new_date)

dt = str(datetime.now())
print(dt)
change_date(dt)

output

2021-06-09 16:15:58.421486
2021-06-09
Rima
  • 1,447
  • 1
  • 6
  • 12
  • Just one difference here. The timestamp is a timestamp string, say like 1601403951777 which represents Tuesday, September 29, 2020. That would be my timestamp string. (https://www.epochconverter.com/) – ENV Jun 09 '21 at 20:26
  • Does this answer your question https://stackoverflow.com/questions/36105232/python-how-to-display-time-as-epoch – Rima Jun 10 '21 at 01:44
0

I would recommend using the .replace method of datetime objects:

def change_date(string: timestamp, string: new_date):
    source_dt = datetime.fromtimestamp(int(timestamp))
    year, month, date = [int(i) for i in new_date.split('-')]
    return f"{source_dt.replace(year=year, month=month, date=date):...}"
    

where {:...} is the format you need.

lonetwin
  • 971
  • 10
  • 17