Python日期时间添加
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18817750/
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 datetime add
提问by Max
I have a datetime value in string format. How can I change the format from a "-" separated date to a "." separated date. I also need to add 6 hours to let the data be in my time zone.
我有一个字符串格式的日期时间值。如何将格式从“-”分隔的日期更改为“.” 分开的日期。我还需要添加 6 小时才能让数据处于我的时区。
s = '2013-08-11 09:48:49'
from datetime import datetime,timedelta
mytime = datetime.strptime(s,"%Y-%m-%d %H:%M:%S")
time = mytime.strftime("%Y.%m.%d %H:%M:%S")
dt = str(timedelta(minutes=6*60)) #6 hours
time+=dt
print time
print dt
I get the following result where it adds the six hours at the end and not to the nine:
我得到以下结果,它在最后添加了六个小时而不是九个小时:
2013.08.11 09:48:496:00:00
6:00:00
采纳答案by Martijn Pieters
You are adding the string representationof the timedelta()
:
您正在添加 的字符串表示形式timedelta()
:
>>> from datetime import timedelta
>>> print timedelta(minutes=6*60)
6:00:00
Sum datetime
and timedelta
objects, not their string representations; only create a string aftersumming the objects:
Sumdatetime
和timedelta
对象,而不是它们的字符串表示;仅在对对象求和后创建一个字符串:
from datetime import datetime, timedelta
s = '2013-08-11 09:48:49'
mytime = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
mytime += timedelta(hours=6)
print mytime.strftime("%Y.%m.%d %H:%M:%S")
This results in:
这导致:
>>> from datetime import datetime, timedelta
>>> s = '2013-08-11 09:48:49'
>>> mytime = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
>>> mytime += timedelta(hours=6)
>>> print mytime.strftime("%Y.%m.%d %H:%M:%S")
2013.08.11 15:48:49
However, you probably want to use real timezone objects instead, I recommend you use the pytz
library:
但是,您可能想改用实时时区对象,我建议您使用pytz
库:
>>> from pytz import timezone, utc
>>> eastern = timezone('US/Eastern')
>>> utctime = utc.localize(datetime.strptime(s, "%Y-%m-%d %H:%M:%S"))
>>> local_tz = utctime.astimezone(eastern)
>>> print mytime.strftime("%Y.%m.%d %H:%M:%S")
2013.08.11 15:48:49
This will take into account daylight saving time too, for example.
例如,这也将考虑夏令时。