I got one problem with UNIX time to human readable time. In fact I was also thinking is it possible to conterte UNIX time to Comma-separated-values...so that I can make a plot based on this converted real time and the corresponding values.
But my UNIX is in int64 format, I tried using
unix_epoch = datenum(1970,1,1,0,0,0);
for i=1:1:size(data_mat)
matlab_time(i,1) = data_mat(i,1)./86400 + unix_epoch;
end
for example: 1352434077. So when I tried to converte it with this code: It gave 735087..not something like YYYY-MM-DD: hh:mm:ss ...can anyone gave me a hint? Thanks a lot!
You need to use datestr (the output of which is a string):
>> time_num = 735087
time_num = 735087
>> datestr(time_num)
ans = 06-Aug-2012
You can also specify a format for the output, such as 'dd-mmm-yyyy HH:MM:SS', check the doc.
Related
I've looked for help on the internet for the following, but I could not find a satisfying answer: for an assignment, I need to plot the time series of a certain variable (the term spread in percentages), with years on the x-axis.
However, we use daily data. Does anybody know a convenient way in which this can be done? The 'date' variable that I've got is formulated in the following way: 20111017 represents the 17th of October 2011.
I tried to extract the first 4 numbers of the variable 'date', by using the substr(date, 1, 4) command, but the message 'type mismatch' popped up. Also, I'm not quite sure if it gives the right information if I only use the years to plot daily data (over the years). It now gives the following graph, which doesn't look that nice.
Answering the question in your title.
The date() function expects a string. If your variable with value 20111017 is in a numeric format you can convert it like this: tostring datenum , gen(datestr).
Then when using the date() function you must provide a mask that tells Stata what format the date string is in. Below is a reproducible example you can run to see how this works.
* Example generated by -dataex-. For more info, type help dataex
clear
input float datenum
20111016
end
* Convert numberic varaible to string
tostring datenum , gen(datestr)
* Convert string to date
gen date = date(datestr, "YMD")
* Display date as date
format date %td
If this does not help you, try to provide a reproducible example.
This adds some details to the helpful answer by #TheIceBear.
As he indicates, one way to get a Stata daily date from your run-together date variable is convert it to a string first. But tostring is just one way to do that and not essential. (I have nothing against tostring, as its original author, but it is better suited to other tasks.)
Here I use daily() not date(): the results are identical, but it's a good idea to use daily(): date() is all too often misunderstood as a generic date function, whereas all it does is produce daily dates (or missings).
To get a numeric year variable, just divide by 10000 and round down. You could convert to a string, extract the first 4 characters, and then convert to numeric, but that's more operations.
clear
set obs 1
gen long date = 20111017
format date %8.0f
gen ddate = daily(strofreal(date, "%8.0f"), "YMD")
format %td ddate
gen year = floor(date/10000)
list
+-----------------------------+
| date ddate year |
|-----------------------------|
1. | 20111017 17oct2011 2011 |
+-----------------------------+
I want to assign the current year in a YY format to either a macro or data set variable.
I am able to use the automatic macro variables &sysdate or &sysdate9 to get the current date. However, extracting the year in a YY format is proving to be a nightmare. Below are some examples of what I've been trying.
There exists the YEARw. format. But when I try to use it I get errors or weird results. For instance, running
data _null_;
yy = year(input("&sysdate9.", year2.));
put yy=;
run;
produces the error
ERROR 48-59: The informat YEAR was not found or could not be loaded.
If I try to format the variable in the output, I get 1965 instead of the current year. The following
data _null_;
yy = year(input("&sysdate9.", date9.));
put yy= yy year2.;
run;
outputs
yy=2016 65
Please help.
This works to get you the 2-digit year number of the current year:
DATA _NULL_;
YEAR = PUT(TODAY(),YEAR2.);
PUT YEAR;
RUN;
/* Returns: 16 */
To breakdown what I am doing here:
I use TODAY() to get the current date as a DATE type. &SASDATE needs to be converted to a DATE, but also it is the date that the SAS session started. TODAY() is the current date.
PUT allows us to pass in a non-character (numeric/date) value, which is why it is used with TODAY() as opposed to INPUT.
I think it is worth exploring the issues here in more detail.
First, Formats are patterns for converting numeric values to a human readable format. That's what you want to do here: convert a date value to a human readable format, in this case to a year.
Informats, on the other hand, convert human readable information to numeric values. That's not what you're doing here; you have a value already.
Second, put matches with Formats, and input matches with informats, exclusively.
Third, you get close in your last try: but you misuse the year format. Formats are basically value mappings, so they map every possible numeric value in their range (sometimes "all values" is the range, sometimes not) to a display value (string). You need to know what kind of value is expected on the input. YEARw. expects a date value as input, not a year value: meaning input is "number of days from 1/1/1960", mapped to "year". So you cannot take a value you've already mapped to a year value and map it again with that method; it will not make any sense.
Let's look at it:
data _null_;
yy = year(input("&sysdate9.", date9.));
put yy= yy year2.;
run;
yy contains the result of the year function - 2016. Good so far. Now, you need the 2 digit year (16); you can get that through mod function, if you like, or put/substr/input:
data _null_;
yy = input(substr(put(year(input("&sysdate9.", date9.)),4.),3,2),2.);
put yy=;
run;
mod is probably easier though since it's a number. But of course you could've used year:
data _null_;
yy = put(input("&sysdate9.", date9.),year2.);
put yy=;
run;
Now, yy is character, so you could wrap that with input(...,2.) or leave it character depending on your purposes.
Finally - a use note on &sysdate9.. You can easily make this a date without input:
"&sysdate9."d
So:
yy = put("&sysdate9."d,year2.);
That's called a date literal (and "..."dt and "..."t also work for datetime,time). They require things in the standard SAS formats to work properly.
And as pointed out in Nicarus' answer, today() is a bit better than &sysdate9 since it is guaranteed to be today. If you're running this in batch or restart your session daily, this won't matter, but it will if you have a long-running session.
Apply the year function to the date variable
Convert to string
Take last 2 digits
EDIT: change input to PUT
Year = substr(put(year(today()), 4.), 3);
I want to ask a simple question about datatime format in matlab.
I know "HH:MM:SS:SSS"is like "Hour:Minute:Second:MillisSecond".What if I just need "MM:SS:SSS". Is this possible in matlab?
Can I use the following code in my program?
dt = datestr(A,'MM:SS:SSS')
Thanks.
What I am trying to do is add a timestamp at each line of my output txt.
The first line is "00:00:000"
The second line is "00:00:100"
Correct me if i'm wrong, but there's no SSSS for MillisSecond with datetime format in Matlab. You should read more carefully here.
In case you need MillisSecond, you have to use FFF, and you can only get MillisSecond in 3 digits:
datestr(rem(now, 1), 'MM:SS:FFF');
At the moment I am using xlsread to open a set of data that I have in excel with given timestamps. But when these values are placed in matlab it changes the formatting of the timestamp.
In excel it is:
dd/mm/yyyy HH:MM
but when it puts it into matlab it changes it to
mm/dd/yyyy HH:MM
which ruins my other code. I have tried using formatIn and specifying it, but then it returns an error if no value for midnight is given.
Any help would be appreciated.
You can use datenum and datestr to convert the format to what you want. In the following example I'm assuming your timestamps are contained in a cell array of strings, but it also works if it's a char matrix:
>> timestamps = {'08/25/2014 13:14'; '08/26/2014 14:15'} %// mm/dd/yyyy HH:MM
>> result = datestr(datenum(timestamps, 'mm/dd/yyyy HH:MM'), 'dd/mm/yyyy HH:MM')
result =
25/08/2014 13:14
26/08/2014 14:15
What Luis recommended should help you to get any format that you like. However there is something important to realize here:
Excel does not 'have' the date in your format. It has the date stored as a number like 123546.123 and presents it to you in a certain way.
If you want to get the date in exactly the way that excel presents it, the trick is to avoid importing the relevant column as a date, but just import it as text instead.
How to do this depends on your import method, but it should not be very hard.
Disclaimer: you might need to install
a font/typeface which supports
Japanese if you see messed up
characters.
I'm trying to replicate what I've been doing so far with setlocale and strftime:
setlocale(LC_ALL, 'ja_JP.utf8');
$time = mktime();
echo strftime('%x', $time), '<br>';
Output:
2010年01月06日
Using Zend_Date - but I haven't been able to reproduce the same formatting with the japanese symbols for year, month and day.
Attempt #1:
$locale = new Zend_Locale('ja_JP');
$date = new Zend_Date( strtotime('yesterday'), null, $locale);
//echo $date->toString('YYYY abcdefghijklmnopqrstuvwxy M dE');
echo $date->get('YYYY MMM DD');
Output:
2010 1月 004
Attempt #2:
echo $date->get(Zend_Date::DATE_FULL);
Output:
2010年1月5日火曜日
My first attempt I can't seem to find a working constant to produce the YEAR and day symbols. The latter uses a standardized format but I need to customize it so there's a 0 preceding the month, and I want to be more in control.
In the future I may want to make it flexible so for example, en_US dates won't have those letters coming after the year/month/day but it would only apply to languages such as Japanese and others, where it's more common, or if I misunderstood and it isn't really common then please inform me.
Thanks in advance.
Seems what I needed was the DATE_LONG constant, which internally points to 'FFFF' - I'm trying to learn the inner workings of how the Date class corresponds with the Locale class to generate the whole string including the symbols now.
Update: I kept trying to find where it actually used date units instead of date formats, found the right data I need:
<dateFormatLength type="long">
<dateFormat>
<pattern>y年M月d日</pattern>
</dateFormat>
</dateFormatLength>
So it parses this and replaces the y, M, d, returns the formatted date.