Python日期时间添加 [英] Python datetime add
问题描述
我有一个字符串格式的datetime值。如何将格式从-分隔的日期更改为。。分居日期。我还需要添加6个小时才能使数据位于我的时区。
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.
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
推荐答案
您正在添加 timedelta()
的字符串表示形式:
>>> from datetime import timedelta
>>> print timedelta(minutes=6*60)
6:00:00
总和 datetime
和 timedelta
对象,而不是它们的字符串表示形式;仅在对对象求和之后之后创建一个字符串:
Sum datetime
and timedelta
objects, not their string representations; only create a string after summing the objects:
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")
这将导致:
>>> 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
但是,您可能想使用实时区对象,我建议您使用 pytz
库:
However, you probably want to use real timezone objects instead, I recommend you use the pytz
library:
>>> 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.
这篇关于Python日期时间添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!