从带有今天/明天日期的时间字符串中获取时间戳

时间:2019-07-20 11:09:43

标签: python date datetime time timestamp

在将时间字符串转换为时间戳时需要一些帮助。假设我的时间是07:00:00,如何在当前日期之后加上时间戳?

当前我有datetime.strptime('07:00:00', '%H:%M:%S'),但返回1900-01-01 07:00:00

7 个答案:

答案 0 :(得分:1)

好吧,这样的事情应该起作用:

from datetime import datetime as dt

today = dt.today()
time = dt.strptime('07:00:00', '%H:%M:%S')

time = time.replace(day=today.day, month=today.month, year=today.year)

print(time) # datetime.datetime(2019, 7, 20, 7, 0)

答案 1 :(得分:0)

您可能要检查this page

from datetime import datetime
# current date and time
now = datetime.now()
timestamp = datetime.timestamp(now)
print("timestamp =", timestamp)

答案 2 :(得分:0)

您可以尝试更换today的零件:

from datetime import datetime
today = datetime.today()
mytime = '07:00:00'

then = today.replace(**dict(zip(['hour', 'minute','second'], map(int, mytime.split(':')))))
print(then)

输出:

2019-07-20 07:00:00.108203

答案 3 :(得分:0)

尝试一下

import datetime as dt_lib
from dateutil import parser as date_parser

def get_upcoming_7_o_clock_timestamp():
    today = dt_lib.datetime.now()
    upcoming_7_o_clock = date_parser.parse(today.date().isoformat() + ' ' + '07:00:00')


    if today > upcoming_7_o_clock:
        upcoming_7_o_clock = date_parser.parse((today + dt_lib.timedelta(days=1)).date().isoformat() + ' ' + '07:00:00')
    return upcoming_7_o_clock

答案 4 :(得分:0)

您可以尝试

Generalized Pareto distribution
http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.genpareto.html

Fit Statistics for 16 data points:
    Negative Two Log Likelihood = -1.3852573661570938E+02
    AIC = -1.3252573661570938E+02
    AICc (Burnham and Anderson) = -1.3052573661570938E+02


Parameters:
    c = -3.7800889226684840E+00
    location = 1.0213689198388039E+02
    scale = 3.5222118656995849E-01

输出-

  

1563586200

答案 5 :(得分:0)

您可以将今天的日期添加到您的时间中,然后应用strptime

from datetime import date, datetime


my_datetime = f"07:00:00 {date.today()}"
print(datetime.strptime(my_datetime, "%H:%M:%S %Y-%m-%d"))
# 2019-07-20 07:00:00

答案 6 :(得分:-1)

这似乎是避免将日期愚蠢地双重转换为字符串和字符串的简单方法:

import datetime

date = datetime.datetime.now()
time = datetime.datetime.strptime( '07:00:00', '%H:%M:%S').time()

datetime.datetime.combine( date, time )

给予:

datetime.datetime(2019, 7, 20, 7, 0)

(最好使用datetime作为变量名,但是为了清楚起见... =)