【问题标题】:How to increase timestamp string to timestamp with new year, month, day Python datetime?如何使用新的年、月、日 Python 日期时间将时间戳字符串增加到时间戳?
【发布时间】:2021-06-09 19:55:05
【问题描述】:

我想编写一个函数,它接收一个表示时间戳的字符串,然后更改该时间戳的年、月和日,而不是实际时间。然后我想将生成的时间戳作为字符串返回。我在转换时遇到了一些问题,因为我认为我需要按以下顺序进行转换:字符串 -> 时间戳 -> 日期 -> 时间戳 -> 字符串。我已经阅读了 datetime 库,但我在转换时遇到了一些问题。任何帮助,将不胜感激!

函数输入如下所示:

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

例如时间戳 1601403951777 是 2020 年 9 月 29 日,星期二。

【问题讨论】:

标签: python date datetime


【解决方案1】:

试试这个,

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)

输出

2021-06-09 16:15:58.421486
2021-06-09

【讨论】:

【解决方案2】:

我建议使用日期时间对象的.replace 方法:

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):...}"
    

{:...} 是您需要的格式。

【讨论】:

  • int(timestamp) / 1000 因为您需要将总秒数的浮点数传递给fromtimestamp()
猜你喜欢
  • 2022-01-03
  • 2023-03-31
  • 2012-10-25
  • 2010-11-01
  • 2014-11-18
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
  • 2021-06-27
相关资源
最近更新 更多