source: TI02-CSML/trunk/csml/csmllibs/csmltime.py @ 2357

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI02-CSML/trunk/csml/csmllibs/csmltime.py@2357
Revision 2357, 6.3 KB checked in by domlowe, 13 years ago (diff)

Times now formatted correctly

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#!/usr/bin/env python
2
3#**************************************************************************************
4#csmltime.py
5#contains time related functions for creating CSML
6#v0.5 split off 11th November 2005
7#v0.51 updated to use datainterface 6th Dec 05
8#!!!!!!!!!!!!!!! NEEDS TIDYING UP!!!!!!!!!!!!!!!!!!!!!!!!!!!
9#Dominic Lowe, BADC
10#**************************************************************************************
11
12import csml.csmllibs
13import datetime
14import sys
15import cdtime
16import pdb
17
18def CSMLtimeToUDtime(time):
19        #time string manipulation  - convert  2783-5-22T0:0:0.0 to 2783-5-22 0:0:0.0
20    return str(time).replace ('T', ' ')
21
22def UDtimeToCSMLtime(time):
23    #time string manipulation  - convert 2783-5-22 0:0:0.0 to 2783-5-22T0:0:0.0
24    newdate=''
25    newtime=''
26    date = str(time).split()[0]
27    t=str(time).split()[1]
28    for item in date.split('-'):
29        if len(item)==1:
30            item='0'+item
31        newdate=newdate + item +'-'
32    for item in t.split(':'):
33        if len(item)==1:
34            item='0'+item+':'
35        elif len(item)==3:
36            item='0'+item
37        newtime=newtime + item
38    csmlt=newdate[:-1]+'T'+newtime
39    return str(csmlt)
40               
41def setcdtimeCalendar(cal):
42    if cal == 'standard':
43        cdtime.DefaultCalendar= cdtime.MixedCalendar
44    elif cal == 'gregorian':
45        cdtime.DefaultCalendar= cdtime.MixedCalendar
46    elif cal == 'proleptic_gregorian':
47        cdtime.DefaultCalendar= cdtime.GregorianCalendar
48    elif cal=='360_day':
49        cdtime.DefaultCalendar=cdtime.Calendar360
50    elif cal=='noleap':
51        cdtime.DefaultCalendar=  cdtime.NoLeapCalendar
52    elif cal=='365_day':
53        cdtime.DefaultCalendar=  cdtime.NoLeapCalendar
54    elif cal =='julian':
55        cdtime.DefaultCalendar=  cdtime.JulianCalendar
56       
57       
58def identifyTimeAxis(self,listToCheck): 
59    #given a list of possible axes, find the one which is most probably the time axis.
60    for name in listToCheck:
61        if string.upper(name) in ['T', 'TIME']:
62            tname =name
63    return tname
64
65def compareTimes(timemin, timecheck, timemax):
66    timeok=0
67    try:
68        year=int(timecheck.split('-')[0])
69        month=int(timecheck.split('-')[1])
70        day=int(timecheck.split('-')[2].split('T')[0])
71        tcheck=cdtime.comptime(year,month,day)
72        timeok=0
73        if tcheck.cmp(timemin) >= 0:
74            if tcheck.cmp(timemax) < 1:
75                timeok = 1
76    except:
77        #if it's not a proper internet time e.g. time = '6' then just compare numerically
78        timeok=0
79        if timecheck >=timemin:
80            if timecheck <=timemax:
81                timeok = 1
82    return timeok
83
84def getTimeAsValue(time):
85    year=int(time.split('-')[0])
86    month=int(time.split('-')[1])
87    day=int(time.split('-')[2].split('T')[0])
88    hour=int(time.split('-')[2].split('T')[1].split(':')[0])
89    minute=int(time.split('-')[2].split('T')[1].split(':')[1])
90    second=float(time.split('-')[2].split('T')[1].split(':')[2])
91    return (10000000000*year+100000000*month + (1000000 * day) + (10000*hour) + (100*minute) + second)
92
93def convertValueToCSML(t):
94    #this may need to be more robust
95    csmlt='%s-%s-%sT%s:%s:%s.%s'%(int(t/10000000000),str(int(t/100000000))[-2:],str(int(t/1000000))[-2:]
96,str(int(t/10000))[-2:],str(int(t/100))[-2:],str(int(t))[-2:],0)
97    return csmlt
98
99
100def getCDtime(time): 
101    year=int(time.split('-')[0])
102    month=int(time.split('-')[1])
103    day=int(time.split('-')[2].split('T')[0])
104    hour=int(time.split('-')[2].split('T')[1].split(':')[0])
105    minute=int(time.split('-')[2].split('T')[1].split(':')[1])
106    second=float(time.split('-')[2].split('T')[1].split(':')[2])
107    cdTimeVal=cdtime.comptime(year,month,day,hour,minute,second)
108    return cdTimeVal
109
110def getFileTimeList(filelist, timedim):
111        #****************************************************************************************
112        #Given a list of files and a name for the time dimension this function will return a list containing
113        # filename/time pairs eg tuple [(ta,fa),(tb,fb),(tc,fc)] in the correct temporal order.
114        #if files contain more than one time, then the tuple will be of the form:
115        #[(ta1,ta2,ta3,fa),(tb1,tb2,tb3,fb),(tc1,tc2,tc3,fc)]
116        #*****************************************************************************************
117        FileTimeList = []  #list to hold the filesnames and corrsponding times
118        DI=csml.csmllibs.csmldataiface.DataInterface()
119        #grab any (first) file                 
120        DI=DI.getUnknownInterfaceType(filelist[0])
121        count=0
122        for file in filelist:
123                count=count +1
124                DI.openFile(file)
125                try:
126                        DI.setAxis(timedim)
127                        data =DI.getDataForAxis()
128                except:
129                        try:
130                            data=DI.getTimes()
131                        except:
132                            print 'tried alternative method to get time axis and failed'
133                            print "check you have the correct time axis (-t) set"
134                            sys.exit()
135                times=[]
136                for j in range(0,len(data)):
137                        times.append(data[j])
138                refTime=DI.getTimeUnits()   #maybe this can be optional?
139                ftTuple = (times, file,refTime)
140                FileTimeList.append(ftTuple)
141                DI.closeFile()
142                if count % 20 == 0:
143                        print 'scanning file %s of %s'%(count,len(filelist))
144        #get calendar type:
145        DI.openFile(filelist[0])
146        try:
147            DI.setAxis(timedim)
148            cal = DI.getAxisAttribute('calendar')
149            setcdtimeCalendar(cal)
150        except:
151            print 'No calendar attribute, defaulting to CF standard mixed calendar'
152            cal='standard'
153            setcdtimeCalendar(cal)
154        try:
155            units=DI.getAxisAttribute('units')
156        except:
157            print "Could not get time unit info"
158            units =''
159        FileTimeList.sort()
160        #get the reference date for the time reference system.
161        #refTime=DI.getTimeUnits()
162        DI.closeFile()
163        FormattedFileTimeList = []
164        for j in range (0,len(FileTimeList)):
165                timeList = FileTimeList[j][0]
166                refTime=FileTimeList[j][2]
167                #print 'timelist_____________________' +str(timeList)
168                for k in range(0, len(timeList)):
169                        relativetime= cdtime.reltime(timeList[k], refTime)
170                        uduTime=UDtimeToCSMLtime(relativetime.tocomp())
171                        ftTuple = (uduTime, filelist[j])
172                        FormattedFileTimeList.append(ftTuple)                   
173        print  'finished time list'
174        return FormattedFileTimeList, cal,units
Note: See TracBrowser for help on using the repository browser.