0

In my NetCDF file I have a group 'vel' containing the variable 'time' that I am using as my X-Axis when plotting with matplotlib and numpy.

I would like the plot X axis as datetime (rather than Unix time), but am not having much success from other code examples. I am not sure if it is better to do it inline during the plot creation, or perform a function on the variable and create a new data item/variable. Also, the Unix time is not an integer (decimal seconds - see below example)

1,1665583266.0000
2,1665583266.0625
3,1665583266.1250
4,1665583266.1875
5,1665583266.2500
6,1665583266.3125
7,1665583266.3750
8,1665583266.4375
9,1665583266.5000
10,1665583266.5625

Tried using variations of datetime.datetime.fromtimestamp(YOUR_UNIX_TIMESTAMP)

But got errors as below:

Only length-1 arrays can be converted to Python scalars

Not seen any examples of doing time conversion on NetCDF dataset

This clearly works on a single data item as the following works as expected and returns todays date/time of 2022-12-22 13:23:35:

import datetime
 
unixToDatetime = datetime.datetime.fromtimestamp(1671715415) # Unix Time
print(unixToDatetime)
6
  • 2
    This question has several problems in it - please limit it to a single issue so it can be applicable to many people. Commented Dec 21, 2022 at 17:38
  • Welcome to SO. Questions should not have multiple questions. Please also give users a way to reproduce the problem. Also, do not assume people know what Unix time is. State clearly what the time format is to make it easy for someone to help Commented Dec 21, 2022 at 19:54
  • Unixtime is time in seconds since Jan 01 1970 Commented Dec 22, 2022 at 13:20
  • Removed the second question Commented Dec 22, 2022 at 13:22
  • Added example code that works with a single defined data item, but need to adapt it to work on a NetCDF table variable Commented Dec 22, 2022 at 13:33

1 Answer 1

2

Okay, I worked out how to do it with Pandas:

import netCDF4
import pandas as pd

nc = netCDF4.Dataset('filename.nc')
tvel = nc.groups['vel'].variables['time'][:] # Unix time
dt_tvel = pd.to_datetime(tvel, unit='s') # Datetime

print(dt_tvel)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.