Python 将秒转换为 datetime 日期和时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45140034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python convert seconds to datetime date and time
提问by tushariyer
How do I convert an int like 1485714600
such that my result ends up being Monday, January 30, 2017 12:00:00 AM
?
我如何转换一个 int1485714600
这样我的结果最终是Monday, January 30, 2017 12:00:00 AM
?
I've tried using datetime.datetime
but it gives me results like '5 days, 13:23:07'
我试过使用,datetime.datetime
但它给我的结果是 '5 days, 13:23:07'
采纳答案by Alexander Ejbekov
Like this?
像这样?
>>> from datetime import datetime
>>> datetime.fromtimestamp(1485714600).strftime("%A, %B %d, %Y %I:%M:%S")
'Sunday, January 29, 2017 08:30:00'
回答by Willem Van Onsem
What you describe here is a (Unix) timestamp(the number of seconds since January 1st, 1970). You can use:
您在此处描述的是(Unix) 时间戳(自 1970 年 1 月 1 日以来的秒数)。您可以使用:
datetime.datetime.fromtimestamp(1485714600)
This will generate:
这将生成:
>>> import datetime
>>> datetime.datetime.fromtimestamp(1485714600)
datetime.datetime(2017, 1, 29, 19, 30)
You can get the nameof the day by using .strftime('%A')
:
您可以使用以下命令获取当天的名称.strftime('%A')
:
>>> datetime.datetime.fromtimestamp(1485714600).strftime('%A')
'Sunday'
Or you can call weekday()
to obtain an integers between 0
and 6
(both inclusive) that maps thus from monday to sunday:
或者,您可以调用weekday()
以获取从星期一到星期日映射的0
和之间的整数6
(包括两者):
>>> datetime.datetime.fromtimestamp(1485714600).weekday()
6