Convert datetime string to a different datetime string in PowerShell v2 - datetime

I have the following string which is pulled from an entry in a log file.
$d = "19/09/2014 22:41:27"
However, I need to convert it so that it is
2014-09-19 22:41:27
so that I can export it with other sections of the logfile into a MySQL database.
But I can't for the life of me find a way to do this. I was expecting to find something like set-dateFormat, which would simply re-map the components of the string, but it doesn't seem to exist.
I have tried various variations of the following:
$a = "19/09/2014 22:41:27"
$d = [datetime]::ParseExact($a, "dd/MM/yyyy hh:mm:ss", $null)
$e = "{0:yyyymmddhhmmss}" -f [datetime]$d
But everything returns the error:
String was not recognized as a valid DateTime.
What is the best way to get the format I need please?

A quick play around, with the help of a few other blogs provided the following, very similar to your own. There's probably a way to make it a little more streamlined, but it will create the datetime object you need. Manipulating the output after that should be straightforward.
$theDTString = "19/09/2014 22:41:27".toString()
$theDateTimeObject = ([datetime]::ParseExact($theDTString,"dd/MM/yyyy HH:mm:ss",$null))
$theDateTimeObject.year.toString() + "-" + $theDateTimeObject.month.toString() +"-"+
$theDateTimeObject.day.toString() + " " + $theDateTimeObject.Hour.toString() + ":" +$theDateTimeObject.Minute.toString() + ":" + $theDateTimeObject.Second.toString()

The identical answer to your original input is this:
$a = "19/09/2014 22:41:27"
$d = [datetime]::ParseExact($a, "dd/MM/yyyy HH:mm:ss", $null)
$e = "{0:yyyymmddhhmmss}" -f [datetime]$d
It was having an error trying to convert hour 22 as a 12 Hour format.

Related

String recognition in idl

I have the following strings:
F:\Sheyenne\ROI\SWIR32_subset\SWIR32_2005210_East_A.dat
F:\Sheyenne\ROI\SWIR32_subset\SWIR32_2005210_Froemke-Hoy.dat
and from each I want to extract the three variables, 1. SWIR32 2. the date and 3. the text following the date. I want to automate this process for about 200 files, so individually selecting the locations won't exactly work for me.
so I want:
variable1=SWIR32
variable2=2005210
variable3=East_A
variable4=SWIR32
variable5=2005210
variable6=Froemke-Hoy
I am going to be using these to add titles to graphs later on, but since the position of the text in each string varies I am unsure how to do this using strmid
I think you want to use a combination of STRPOS and STRSPLIT. Something like the following:
s = ['F:\Sheyenne\ROI\SWIR32_subset\SWIR32_2005210_East_A.dat', $
'F:\Sheyenne\ROI\SWIR32_subset\SWIR32_2005210_Froemke-Hoy.dat']
name = STRARR(s.length)
date = name
txt = name
foreach sub, s, i do begin
sub = STRMID(sub, 1+STRPOS(sub, '\', /REVERSE_SEARCH))
parts = STRSPLIT(sub, '_', /EXTRACT)
name[i] = parts[0]
date[i] = parts[1]
txt[i] = STRJOIN(parts[2:*], '_')
endforeach
You could also do this with a regular expression (using just STRSPLIT) but regular expressions tend to be complicated and error prone.
Hope this helps!

Format datetime day with st, nd, rd, th

I'm creating a report in SSRS and across the top I have a header with a placeholder for "Last Refreshed" which will show when the report last ran.
My function in the placeholder is simply this:
=Format(Now, "dddd dd MMMM yyyy hh:mm tt")
Which looks like this:
Monday 22 September 2015 09:46 AM
I want to format the day value with the English suffix of st, nd, rd and th appropriately.
I can't find a built in function for this and the guides I've looked at so far seem to describe doing it on the SQL side with stored procedures which I don't want. I'm looking for a report side solution.
I thought I could get away with an ugly nested IIF that did it but it errors out despite not giving me any syntax errors (whitespace is just for readability).
=Format(Now, "dddd " +
IIF(DAY(Now) = "1", "1st",
IIF(DAY(Now) = "21","21st",
IIF(DAY(Now) = "31","31st",
IIF(DAY(Now) = "2","2nd",
IIF(DAY(Now) = "22","22nd",
IIF(DAY(Now) = "3","3rd",
IIF(DAY(Now) = "23","23rd",
DAY(Now) + "th")))))))
+ " MMMM yyyy hh:mm tt")
In any other language I would have nailed this ages ago, but SSRS is new to me and so I'm not sure about how to do even simple string manipulation. Frustrating!
Thanks for any help or pointers you can give me.
Edit: I've read about inserting VB code into the report which would solve my problem, but I must be going nuts because I can't see where to add it. The guides say to go into the Properties > Code section but I can't see that.
Go to layout view. Select Report Properties.Click on the "Code" tab and Enter this code
Public Function ConvertDate(ByVal mydate As DateTime) as string
Dim myday as integer
Dim strsuff As String
Dim mynewdate As String
'Default to th
strsuff = "th"
myday = DatePart("d", mydate)
If myday = 1 Or myday = 21 Or myday = 31 Then strsuff = "st"
If myday = 2 Or myday = 22 Then strsuff = "nd"
If myday = 3 Or myday = 23 Then strsuff = "rd"
mynewdate = CStr(DatePart("d", mydate)) + strsuff + " " + CStr(MonthName(DatePart("m", mydate))) + " " + CStr(DatePart("yyyy", mydate))
return mynewdate
End function
Add the following expression in the required field. I've used a parameter, but you might be referencing a data field?
=code.ConvertDate(Parameters!Date.Value)
Right Click on the Textbox, Go To Textbox Properties then, Click on Number tab, click on custom format option then click on fx button in black.
Write just one line of code will do your work in simpler way:
A form will open, copy the below text and paste there to need to change following text with your database date field.
Fields!FieldName.Value, "Dataset"
Replace FieldName with your Date Field
Replace Dataset with your Dateset Name
="d" + switch(int(Day((Fields!FieldName.Value, "Dataset"))) mod
10=1,"'st'",int(Day((Fields!FieldName.Value, "Dataset"))) mod 10 =
2,"'nd'",int(Day((Fields!FieldName.Value, "Dataset"))) mod 10 =
3,"'rd'",true,"'th'") + " MMMM, yyyy"
I found an easy way to do it. Please see example below;
= DAY(Globals!ExecutionTime) &
SWITCH(
DAY(Globals!ExecutionTime)= 1 OR DAY(Globals!ExecutionTime) = 21 OR DAY(Globals!ExecutionTime)=31, "st",
DAY(Globals!ExecutionTime)= 2 OR DAY(Globals!ExecutionTime) = 22 , "nd",
DAY(Globals!ExecutionTime)= 3 OR DAY(Globals!ExecutionTime) = 23 , "rd",
true, "th"
)

IndexError: list index out of range, scores.append( (fields[0], fields[1]))

I'm trying to read a file and put contents in a list. I have done this mnay times before and it has worked but this time it throws back the error "list index out of range".
the code is:
with open("File.txt") as f:
scores = []
for line in f:
fields = line.split()
scores.append( (fields[0], fields[1]))
print(scores)
The text file is in the format;
Alpha:[0, 1]
Bravo:[0, 0]
Charlie:[60, 8, 901]
Foxtrot:[0]
I cant see why it is giving me this problem. Is it because I have more than one value for each item? Or is it the fact that I have a colon in my text file?
How can I get around this problem?
Thanks
If I understand you well this code will print you desired result:
import re
with open("File.txt") as f:
# Let's make dictionary for scores {name:scores}.
scores = {}
# Define regular expressin to parse team name and team scores from line.
patternScore = '\[([^\]]+)\]'
patternName = '(.*):'
for line in f:
# Find value for team name and its scores.
fields = re.search(patternScore, line).groups()[0].split(', ')
name = re.search(patternName, line).groups()[0]
# Update dictionary with new value.
scores[name] = fields
# Print output first goes first element of keyValue in dict then goes keyName
for key in scores:
print (scores[key][0] + ':' + key)
You will recieve following output:
60:Charlie
0:Alpha
0:Bravo
0:Foxtrot

check if a string's first 16 char is a number

I'm storing some files in database which has filename like 1839341255115211butterflies.jpg.I need to show this filename to the user as butterflies.jpg.I need to remove the first 16 digit and then show the filename.Added to it I also have few filenames which don't have this 16digit addition prior to the filename.Now my question is how do I identify if this string has 16digit numeric value prior to the filename, based on it remove the 1st 16digit and display just the filename. I'm aware of how to remove the first 16digit and retrive the filename but need help on how to identify a string that has 16digit.
Any suggestion is much appreciated.
A regular expression looks like a good fit here:
^[0-9]{16}
The above will match on strings that start with 16 digits (0 to 9).
Usage:
if(Regex.Match(fileName, #"^[0-9]{16}").Success)
{
fileName = fileName.Remove(0, 16);
}
string.Remove will work quite nicely:
var str = "1839341255115211butterflies.jpg";
str = str.Remove(0, 16);
Console.WriteLine(str);
With Linq:
remove all digits at the beginning until 16 digits:
string file = "1839341255115211butterflies.jpg";
string extension = Path.GetExtension(file);
string fileName = Path.GetFileNameWithoutExtension(file);
fileName = new string(fileName.Where((c, i) => i >= 17 || !Char.IsDigit(c)).ToArray());
file = fileName + extension;
Demo
Edit: If you just want to know if the first 16 chars are digits, it's easier and more readable:
bool startsWith16Digits = file.Take(16).All(Char.IsDigit);

Converting DATETIME to a human readable date

I'm trying to convert the DATETIME to something that people can actually use. This is the date:
2013-09-05 11:52:10
I'm using:
date("D, d M Y", '2013-09-05 11:52:10');
Is turning into:
Thu, 01 Jan 1970
Makes no sense to me.
You need to turn the date into a timestamp before passing it to date()
$time = strtotime('2013-09-05 11:52:10');
echo date("D, d M Y", $time);
Is this supposed to be PHP code? If so, the correct is
date("D, d M Y", strtotime('2013-09-05 11:52:10'));
If this has to do with MySql, the correct function to use is DATE_FORMAT (however, what you have is invalid MySql syntax). Please clarify.
PHP's date() function can only handle integer timestamp values; it can't process strings as input.
If you need to convert from one string date format to another, you should use the DateTime::CreateFromFormat() method:
$dateObj = DateTime::CreateFromFormat($inputString);
$outputString = $dateObj->Format('D, d M Y');
However, I would recommend writing your query to use MySQL's UNIX_TIMESTAMP() function to get the date into PHP as a numeric timestamp that PHP's date() function can handle:
MySQL:
SELECT UNIX_TIMESTAMP(yourDateField) as yourDateField_timestamp FROM yourTable ...
Then you can write PHP exactly as you wanted:
PHP:
$dateObj = date('D, d M Y', $row['yourDateField_timestamp']);

Resources