python把天数转换为年_Python:将“ 1990年以来的天数”转换为日期时间对象

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

My desired output is a datetime object like so (also GMT +10):

2015-12-01 00:00:00

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!

解决方案

The datetime module's timedelta is probably what you're looking for.

For example:

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)) # >>>

You can then use and/or manipulate the offset object, or convert it to a string representation however you see fit.

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'))

Output:

2015-12-01 00:00:00

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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值