问题描述
我有一个从netCDF文件中提取的时间序列,我正在尝试将其转换为日期时间格式。时间序列的格式为自1990年1月1日00:00:00 +10起的天数(+10为格林尼治标准时间:+10)
I have a time series that I have pulled from a netCDF file and I'm trying to convert them to a datetime format. The format of the time series is in 'days since 1990-01-01 00:00:00 +10' (+10 being GMT: +10)
time = nc_data.variables['time'][:]
time_idx = 0 # first timestamp
print time[time_idx]
9465.0
我想要的输出是像这样的日期时间对象(也是GMT +10):
My desired output is a datetime object like so (also GMT +10):
2015-12-01 00:00:00
尽管我相信我可能使用了错误的方法,但我尝试使用时间模块转换此方法没有太大的成功(我仍然是python和编程的新手)。
I have tried converting this using the time module without much success although I believe I may be using wrong (I'm still a novice in python and programming).
import time
time_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time[time_idx]*24*60*60))
任何建议表示赞赏,
干杯!
Any advice appreciated,Cheers!
推荐答案
datetime
模块的可能就是您想要的。
The datetime
module's timedelta
is probably what you're looking for.
例如:
from datetime import date, timedelta
days = 9465 # This may work for floats in general, but using integers
# is more precise (e.g. days = int(9465.0))
start = date(1990,1,1) # This is the "days since" part
delta = timedelta(days) # Create a time delta object from the number of days
offset = start + delta # Add the specified number of days to 1990
print(offset) # >>> 2015-12-01
print(type(offset)) # >>> <class 'datetime.date'>
然后您可以使用和/或操作偏移量对象,或者将其转换为字符串表示形式,但是您可以
You can then use and/or manipulate the offset object, or convert it to a string representation however you see fit.
您可以使用与该日期对象相同的格式,就像您在 time_datetime
中所做的一样:
You can use the same format as for this date object as you do for your time_datetime
:
print(offset.strftime('%Y-%m-%d %H:%M:%S'))
输出:
2015-12-01 00:00:00
例如,如果您使用 date
对象,则可以使用 datetime
对象,而不是使用 datetime
对象
Instead of using a date
object, you could use a datetime
object instead if, for example, you were later going to add hours/minutes/seconds/timezone offsets to it.
除了两行代码外,代码将与上面相同:
The code would stay the same as above with the exception of two lines:
# Here, you're importing datetime instead of date
from datetime import datetime, timedelta
# Here, you're creating a datetime object instead of a date object
start = datetime(1990,1,1) # This is the "days since" part
注意:尽管您未声明它,但另一个答案表明您可能正在寻找时区感知日期时间。在这种情况下, dateutil
是Python 2中的另一种建议。在Python 3中,您想使用 datetime
模块的。
Note: Although you don't state it, but the other answer suggests you might be looking for timezone aware datetimes. If that's the case, dateutil
is the way to go in Python 2 as the other answer suggests. In Python 3, you'd want to use the datetime
module's tzinfo
.
这篇关于Python:将“ 1990年以来的天数”转换为日期时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!