Changing date format to "%d/%m/%Y" - date

Would like to change the date format. My data frame is shown below and would like to change all the date formats to "%d/%m/%Y".
df:
id bdate wdate ddate
1 09/09/09 12/10/09 2009-09-27

df$ddate <- format(as.Date(df$ddate), "%d/%m/%Y")

df$ddate<-strftime(df$ddate,"%d/%m/%Y")
df$bdate<-strftime(strptime(df$bdate,"%d/%m/%y"),"%d/%m/%Y")
df$wdate<-strftime(strptime(df$wdate,"%d/%m/%y"),"%d/%m/%Y")

Default R action is to treat strings as factors. Of course, an individual setup may differ from defaults. It's a good practice to change variable values to character, and then convert it to date. I often use chron package - it's nice, simple and what matters the most, it does the job. Only downside of this package lays in time zone handling.
If you don't have chron installed, do:
install.packages("chron")
# load it
library(chron)
# make dummy data
bdate <- c("09/09/09", "12/05/10", "23/2/09")
wdate <- c("12/10/09", "05/01/07", "19/7/07")
ddate <- c("2009-09-27", "2007-05-18", "2009-09-02")
# notice the last argument, it will not allow creation of factors!
dtf <- data.frame(id = 1:3, bdate, wdate, ddate, stringsAsFactors = FALSE)
# since we have characters, we can do:
foo <- transform(dtf, bdate = chron(bdate, format = "d/m/Y"), wdate = chron(wdate, format = "d/m/Y"), ddate = chron(ddate, format = "y-m-d"))
# check the classes
sapply(foo, class)
# $id
# [1] "integer"
# $bdate
# [1] "dates" "times"
# $wdate
# [1] "dates" "times"
# $ddate
# [1] "dates" "times"
C'est ca... it should do the trick...

Related

Suppressing unwanted spaces in dates

From reading code from elsewhere, I have a matrix of dates called 'time' that have unwanted spaces that I want removed.
I've tried isspace and regexprep with no luck
time = regexprep(time, '\W', '');
I have about 130000 dates with the following format:
04-July -2017 09:54:30.000
04-July -2017 09:54:31.000
etc
There are two spaces between the end of 'July' to the next dash I want to suppress to:
04-July-2017 09:54:30.000
04-July-2017 09:54:31.000
Replace two or more spaces with nothing:
>> time = {'04-July -2017 09:54:30.000'
'04-July -2017 09:54:31.000'}
>> regexprep(time,' {2,}','')
{'04-July-2017 09:54:30.000'}
{'04-July-2017 09:54:31.000'}
Unless you just want to correct your input file for later usage, you do not necessarily need to correct the input. There are several ways to parse the time directly with the extra spaces:
Let time be:
time = ['04-July -2017 09:54:31.000';
'04-July -2017 09:54:32.000']
Then to directly parse the string representation of the datetime into a MATLAB date serial number you can use:
%% get date in [MATLAB date serial number]
formatIn = 'dd-mmm -yyyy HH:MM:SS.FFF' ;
matlabTime = datenum(time,formatIn)
matlabTime =
736880.412858796
736880.41287037
This serial time representation is not so human readable but it's the fastest thing you can get if you want to do calculations with date/time.
If your goal is simply to correct the string, then you can use the same trick to read the value in, and define exactly which output format you want out:
%% get date in [string]
formatIn = 'dd-mmm -yyyy HH:MM:SS.FFF' ;
formatOut = 'dd-mmm-yyyy HH:MM:SS.FFF' ;
stringTime = datestr(datenum(time,formatIn),formatOut)
stringTime =
04-Jul-2017 09:54:31.000
04-Jul-2017 09:54:32.000
If you want to use the new datetime objects, the input format has a slight different syntax but the operation is roughly the same:
%% get date in [datetime] objects
formatIn = 'dd-MMM -yyyy HH:mm:ss.SSS' ;
t = datetime(time,'InputFormat',formatIn)
t =
04-Jul-2017 09:54:31
04-Jul-2017 09:54:32
Although the MATLAB console display t in human readable format, t is now a datetime object. Check the documentation if you want to use this.
Replace only two white-spaces after a month and preceding a dash (-):
>> date = '04-July -2017 09:54:30.000';
>> regexprep(date, '(\w) -', '$1-')
ans =
'04-July-2017 09:54:30.000'

Add the date of creation to a filename in SystemVerilog

I need to create a report(.txt) and I want to reference each sessions of tests, so I wanted that for each simulations, I add the date to name of my report.
Like Report_01-19-2017-12:53.txt
So far I have been able to create either a file with the date inside with :
$system("date > sDate");
or display it on my simulation software with :
$system("date");
So far,My code look like :
string filename;
reg [8*30:1] data; // the date is of 29 characters in size
string sDate;
integer scan_file,data_file ;
initial begin
$system("date > data");
data_file = $fopen("data", "r");
scan_file = $fscanf(sDate,"%s", data);
$fclose("data");
[...]
filename = {filename,sDate};
Report_Task = $fopen(filename,"a"); [...]
end
sDate contains nothing, date contains the date...
I tried string and reg for filename and sDate
Instead of going through files to get the date, you could use svlib. Chapter 9 of the documentation illustrates how to get information about the current time.
Don't you mean
scan_file = $fscanf(data_file, "%s", sDate);
where, if the read is successful, scan_file will be equal to 1 (the number of items read). (So, you probably didn't want to call it scan_file.)

V\B Script to extract date from a text file and format it

I work on OCR. We extract text from invoices automatically. When the contents of the invoice are extracted they are stored in a text file, and then we write scripts to extract the data from the text file according to our requirements.
One requirement that has got me stuck is, i need to extract the date from a text file which is not written in any particular format. Its written as 12 08 2014 in a line. I need to extract this and print it out in the dd/mm/yyyy format.
Also, the dates can be written in any format, for example 2nd December 2013, 12-12-2013, 12 Aug 2013 and so on...I need to read the date and extract it in the form of dd/mm/yyyy
ORDERED SHIPPED
THE DATE IS IN THE NEXT LINE 28 08 14, I NEED TO EXTRACT THIS AND PRINT IT IN THE DD/MM/YYYY FORMAT
01239751 **28 08 14** 03 09 14 E31192-00 1
CUST.NO. ItN1 R 0 R NO SALE MM
NOM CI WATT VOTRF NO nr CAMMANOF in-W.01M
ADDRESS HERE**strong text**
Te1:(123)123-1234/ Fax:(123)795-1234
Facture / Invoice
OUTPS:R-103958989 CONE:MONS Taws> NET 60 DAYS
SOLD TO / VENDU A SHIPPED TO / EXPEDIE A
Just try assigning to a date. Date functions recognise most dates.
You need a plan based on an idea. My idea is to apply a set of pairs of a regular expression (to cut a date representation from your data) and a conversion function (to make a date out of that cut).
In code:
Option Explicit
' 12-12-2013
Function DMY(oMT)
DMY = DateSerial(CInt(oMT.SubMatches(2)), CInt(oMT.SubMatches(1)), CInt(oMT.SubMatches(0)))
End Function
' CDate will reliably convert the extracted value
Function TrustCDate(oMT)
TrustCDate = CDate(oMT.Value)
End Function
' 12-12-2013
Dim reDMY : Set reDMY = New RegExp
reDMY.Global = True
reDMY.Pattern = "(\d{2})-(\d{2})-(\d{4})"
' collection of re, func pairs
Dim aOps : aOps = Array( _
Array(reDMY, GetRef("DMY")) _
, Array(reDMY, GetRef("TrustCDate")) _
)
Dim sAll : sAll = CreateObject("Scripting.FileSystemObject").OpenTextFile(".\25986937.txt").ReadAll()
Dim aOp
For Each aOp In aOps
Dim oMTS : Set oMTS = aOp(0).Execute(sAll)
If 1 = oMTS.Count Then
Dim dtCut : dtCut = aOp(1)(oMTS(0))
WScript.Echo TypeName(dtCut), dtCut
End If
Next
output:
cscript 25986937.vbs
Date 12.11.2014
Date 11.12.2014
for a file that starts with:
ORDERED SHIPPED
01239751 12-11-2014 03 09 14 E31192-00 1
CUST.NO. ItN1 R 0 R NO SALE MM
By adding/improving RegExps (will your OCR sometimes deliver O (capital letter o) instead of (digit) 0?) and conversion functions (in which cases can you trust CDate?) you should be able to handle most of your input and to identify the cases in which a human being has to deal with freaks.

lua program shows current time

This is a piece of lua script that displays the time. I cannot separate the numbers ie: time.hour, ":",
to basically show hh:mm:ss
time = os.date("*t")
print(time.hour .. time.min .. time.sec)
There are several ways to do this:
Use string concatenation: print(time.hour .. ":" .. time.min .. ":" .. time.sec)
Use formatting: print(("%02d:%02d:%02d"):format(time.hour, time.min, time.sec))
Use table concatenation: print(table.concat({time.hour, time.min, time.sec}, ":"))
When you really need to format your string, my preference would be for #2. For time = {hour = 1, min = 20, sec = 5} this prints:
1:20:5
01:20:05
1:20:5
For simply printing the time - extract what you want (the time) from the full date stamp string:
> os.date():sub(9)
12:30:39
This works on my PC ;). There may be a different date stamp string in your OS.
G
local date = os.date('*t')
local time = os.date("*t")
print(os.date("%A, %m %B %Y | "), ("%02d:%02d:%02d"):format(time.hour, time.min, time.sec))`

How to print date in the format of mm/dd/yyyy in VB

I need to print the date in the format of mm/dd/yyyy.
if the date is 4/24/2009 it should print the date as 04/24/2009.
that is zero padding is also needed..
I used date function to get the current date...but the date is getting in the format of m/dd/yyyy...
Tested in the immediate window and is working for me (output as a comment)
Format(Now, "MM/dd/yyyy") '04/29/2009
Format(Date, "MM/dd/yyyy") '04/29/2009
Format(CStr(Now), "MM/dd/yyyy") '04/29/2009
Format(Date$, "MM/dd/yyyy") '04/29/2009
Format(CDate(Date), "MM/dd/yyyy")'04/29/2009
So whether it is string or datetime should not matter.
Edit: Saw your comment to Fredrik. It doesn't matter how it looks like when you save it to the db table (column date format would be a property of the db and not your program's (or vb's) responsibility). Just format the value as and when you retrieve it from the db.
Note that the "/" character in date formatting functions has a special meaning, as "date separator". This means that i may be replaced with the date separator for the current locale that the program is executed in (here in Sweden it would be replaced with "-" for instance). In order to ensure that you do indeed get the "/" character in the output, I think this would work (I don't have a VB installation to verify with):
Format(date, "MM'/'dd'/'yyyy")
just for the record, escaping the slash will work
Format(dt,"MM\/dd\/yyyy")
Try the next code:
Format(dt,"MM/dd/yyyy")
When you enter date in whatever format it will convert default value so do one thing that in access change your data type date/time to text then it can't affect to your work sure.
I also use VB6 and need to format date in my txt report
this works for me
Format$(Now, "yyyy-mm-dd-00.00.00")
but only if I declare date as string
You can try like this also depending upon your requirement
Dim strDate As String
Dim strDate1() As String
strDate = FormatDateTime(Now, vbGeneralDate)
If InStr(strDate, " ") > 0 Then
strDate1 = Split(strDate, " ")
Dim datDate1 As Date
If Month(strDate1(0)) < 10 Then
txtDate.Text = "0" + strDate1(0)
Else
txtDate.Text = strDate1(0)
End If
Else
End If
Formatting DateTime as a string is straightforward. Often we use format patterns like "HH." But methods like ToShortDateString are also useful.
Example. First we get the current time through DateTime.Now. When you execute these code examples, the current DateTime will be different on your computer.
Here: A format string beginning with MMM (for the month) is used. Look at how the pattern matches up to the output of the program.
VB.NET program that uses format string with DateTime
Module Module1
Sub Main()
' Use current time.
' ... Use a format.
' ... Write to console.
Dim time As DateTime = DateTime.Now
Dim format As String = "MMM ddd d HH:mm yyyy"
Console.WriteLine(time.ToString(format))
End Sub
End Module
Output
Feb Tue 21 13:26 2017
strDate = Format(strDate, "yyyy-mm-dd")
BillTime = Format(BillTime, "hh:mm:ss")