简体   繁体   English

以特定格式在python中计算经过时间

[英]Calculate Elapsed time in python in specific format

I am trying to write a program to determine the time and date corresponding to a elapsed number of seconds since 00: 00: 00 on 1 January 2016. 我正在尝试编写一个程序来确定与自2016年1月1日00:00:00起经过的秒数相对应的时间和日期。

But i wanted my result in specific format. 但是我想要特定格式的结果。 ie should be the corresponding hour (in military time), minute, second, day of the month, month name, year, and day of the week name (Sunday – Saturday). 即应为相应的小时(以军时为单位),分钟,秒,每月的某天,月份的名称,年份和星期几的名称(星期日至星期六)。 for example,output should look like the following 例如,输出应如下所示

23:59:32 2 January 2018 Tuesday 

i tried to code this 我试图编码这个

import time
start = time.time()
#do something
end = time.time()
temp = end-start
print(temp)
hours = temp//3600
temp = temp - 3600*hours
minutes = temp//60
seconds = temp - 60*minutes
print('%d:%d:%d' %(hours,minutes,seconds))

But i could only get the hours, minutes and seconds part, Is there any way i can get the month,year,and week name too ? 但是我只能得到小时,分钟和秒部分,我也可以得到月,年和周的名称吗?

Also i'm trying to handle leap years too.since a leap year has 366 days with 29 days in February. 我也试图处理leap年。因为a年有366天,而2月为29天。 Leap years are years that are evenly divisible by 4, with the exception of those evenly divisible by 100 but not 400. years年是可以除以4的年份,除了可以除以100而不是400的年份。

To format a datetime you can use strftime(). 要格式化日期时间,可以使用strftime()。

import datetime
my_time = datetime.datetime(year=2018, month=1, day=2, hour=23, minute=59,second=32)
print (my_time.strftime("%X %-d %B %Y %A"))

If you want to change the format use this table for reference 如果要更改格式,请使用此表作为参考

You want to use the Datetime Module . 您要使用Datetime模块 Handling dates and times is trickier than it appears! 处理日期和时间要比看起来复杂得多! That's why it's good that Python has datetime handling built-in. 这就是Python内置日期时间处理的好处。 Datetime and timedelta objects account for leap years and leap seconds, and they handle operations like addition and subtraction 'intuitively'. Datetime和timedelta对象占leap年和leap秒,它们“直观地”处理加减运算。

import datetime
def convert_seconds_since_jan_1(seconds):
    JAN_1_2001 = datetime.datetime(year = 2001, month = 1, day = 1)
    added_time = datetime.timedelta(seconds = seconds)    
    return (JAN_1_2001+added_time)

Getting the weekday is simply a matter of string formatting. 获得工作日仅是字符串格式的问题。 Remember that weekdays are modulo 7! 请记住,工作日是模7!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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