Write TDatime to a ROOT File

I want to store some time metadata to a ROOT TFile (not the file creation time in the TFile header).

I tried to use the TDatime class for the time I want to store, but this does not inherit from TObject and so it has no Write() method.

For floats, ints and doubles, I would use TParameter, but there is no TParameter<TDatime>.

I can use TDatime methods to output a string with a given format, then save to a file using TObjString, but is there a more direct approach?

I think best way is store direct UInt_t fDatime data member from TDatime class.

root [] TDatime now
(TDatime &) Tue Jun  2 23:54:15 2020
root [] UInt_t store_dt = now.Get()
(unsigned int) 1703247247
root [] // write store_dt in file (root, ascii, sql, ...)

root [] // store_dt = read from file
root [] Int_t store_date, store_time;
root [] TDatime::GetDateTime(store_dt, store_date, store_time)
root [] store_date
(int) 20200602
root [] store_time
(int) 235415
// or if necessary full functionality of TDatime class
root [] TDatime dt(store_date, store_time)
(TDatime &) Tue Jun  2 23:54:15 2020
// or
root [] TDatime dt2
(TDatime &) Tue Jun  2 23:56:34 2020
root [] dt2.Set(store_date, store_time)
root [11] dt2
(TDatime &) Tue Jun  2 23:54:15 2020

You can save TDatime as UInt_t.

It seems to me that a better idea is to use a TTimeStamp (it internally keeps the time relative to Jan 1, 1970 00:00:00 UTC) and save it e.g. AsDouble or AsString.

Object do not need to inherit from TObject to be stored in a ROOT file :).
So you can use

TDatime now;
TFile *file = ....;
file->WriteObject( &now, "theRecordName" );

Also note that there is already some TDatetime associated with the file:

TFile::GetCreationDate
TFile::GetModificationDate

WriteObject() works perfectly without any conversion. The TDatime object is recoverable with only a cast. E.g. after writing TDatime object with record name “time” to TFile via WriteObject(), one can do:

TFile* f = TFile::Open(...);
TDatime *t = (TDatime*)f->Get("time");
cout << t->AsSQLString() << "\n";

Thanks!

You can tweak the code to have type safety:

TDatime *t = f->Get<TDatime>("time");

which will set t to nullptr if the object named “time” in the file is not a TDatime.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.