How to change time format in NetBeans template - c++

I have a very specific C++ project, and I use a NetBeans.
Reason for it is because we need to have a specific timestamps, and I found NetBeans templates a great tool for inserting an automatic header with all the relevant stuff.
I manage set everything up nicely, but I can't figure out how to set up the time format in the header template.
Currently it shows this:
Created on April 6, 2017, 2:18 PM
But since I work in Central Europe, I need a 24h hour format so I could have something like
Created on 06.04.2017. at 14:18
I found on how to change a date format here, but it doesn't work for times for some reason.
I even tried with using FreeMaker's template language reference, so I created a variable time that looks like this:
<#assign dateTime = .now>
<#assign time = dateTime?time>
${time?iso("Europe/Zagreb")}
But it still didn't change anything.
Now my template looks like this:
// -*- C++ -*-
<#assign licenseFirst = "/*">
<#assign licensePrefix = " * ">
<#assign licenseLast = " */">
<#assign aDateTime = .now>
<#assign time = aDateTime?time>
<#include "${project.licensePath}">
/*
* File: ${NAME}.${EXTENSION}
* Author: ${user}
*
* Created on ${DATE} at ${time?iso("Europe/Zagreb")}
*/
#ifndef ${GUARD_NAME}
#define ${GUARD_NAME}
#endif /* ${GUARD_NAME} */
Is this possible to be changed at all, and how?
Any help is appreciated.

In your question you link a resource (THANKS for that!!!) suggesting the following for dates:
${date?date?string("dd.MM.yyyy")}
I tried the same for time and it works well:
${time?time?string("HH.mm.ss")}
BTW I also tried producing some errors and got some nice error messages stating what NB expects and what it gets pretty clearly:
${date?time?string("hh.mm.ss")}
${time?date?string("hh.mm.ss")}
${time?datetime?string("hh.mm.ss")}
${date?datetime?string("hh.mm.ss")}
produced:
Error: on line 20, column 6 in Templates/Classes/Class.java
The string doesn't match the expected date/time format. The string to parse was: "11-Jan-2018". The expected format was: "HH:mm:ss".
Error: on line 21, column 6 in Templates/Classes/Class.java
The string doesn't match the expected date/time format. The string to parse was: "13:40:27". The expected format was: "dd-MMM-yyyy".
Error: on line 22, column 6 in Templates/Classes/Class.java
The string doesn't match the expected date/time format. The string to parse was: "13:40:27". The expected format was: "dd-MMM-yyyy HH:mm:ss".
Error: on line 23, column 6 in Templates/Classes/Class.java
The string doesn't match the expected date/time format. The string to parse was: "11-Jan-2018". The expected format was: "dd-MMM-yyyy HH:mm:ss".

Related

How to get Current Date in Ballerina

Is there a way to get the current date in ballerina?
As I was browsing through some code examples I came across the syntax to get the current time. Shown below is how to get the current date in Ballerina:
Note: first you have to import the time package given below for this to work.
import ballerina/time;
Then put the following lines of code:
time: Time currentTime = time:[currentTime][2]();
string customTimeString = currentTime.format("dd-MM-yyyy");
This will give the following output:
08-07-2018
This is work for ballerina 0.991 and 1.0 first you have to import the time package
Then it will give the current date if you want to get in a format it will included the code
import ballerina/time;
To get current time
time:Time time = time:currentTime();
string standardTimeString = time:toString(time);
io:println("Current system time in ISO format: ", standardTimeString);
To format the time
string|error customTimeString = time:format(time, "yyyy-MM-dd-E");
if (customTimeString is string) {
io:println("Current system time in custom format: ", customTimeString);
}
y -Years
M -months
d -date
E -day
h -hour
m -Minuit
s -seconds
For Swan Lake Update 3 they seem to have removed the time:currentTime() function.
It seems they have replaced it with time:utcNow().
According to the ballerina documentation,
"The time:Utc is the tuple representation of the UTC. The UTC represents the number of seconds from a specified epoch. Here, the epoch is the UNIX epoch of 1970-01-01T00:00:00Z."
So you can convert this above tuple representation to RFC 3339 timestamp by using,
time:Utc currTime = time:utcNow();
string date = time:utcToString(currTime);
io:println(date);
Then you will get a result like below,
2023-01-14T17:04:15.639510400Z
Using ballerina time library you can convert to other different representations as well.

BadDataError when editing a .dbf file using dbf package

I have recently produced several thousand shapefile outputs and accompanying .dbf files from an atmospheric model (HYSPLIT) on a unix system. The converter txt2dbf is used to convert shapefile attribute tables (text file) to a .dbf.
Unfortunately, something has gone wrong (probably a separator/field length error) because there are 2 problems with the output .dbf files, as follows:
Some fields of the dbf contain data that should not be there. This data has "spilled over" from neighbouring fields.
An additional field has been added that should not be there (it actually comes from a section of the first record of the text file, "1000 201").
This is an example of the first record in the output dbf (retrieved using dbview unix package):
Trajnum : 1001 2
Yyyymmdd : 0111231 2
Time : 300
Level : 0.
1000 201:
Here's what I expected:
Trajnum : 1000
Yyyymmdd : 20111231
Time : 2300
Level : 0.
Separately, I'm looking at how to prevent this from happening again, but ideally I'd like to be able to repair the existing .dbf files. Unfortunately the text files are removed for each model run, so "fixing" the .dbf files is the only option.
My approaches to the above problems are:
Extract the information from the fields that do exist to a new variable using dbf.add_fields and dbf.write (python package dbf), then delete the old incorrect fields using dbf.delete_fields.
Delete the unwanted additional field.
This is what I've tried:
with dbf.Table(db) as db:
db.add_fields("TRAJNUMc C(4)") #create new fields
db.add_fields("YYYYMMDDc C(8)")
db.add_fields("TIMEc C(4)")
for record in db: #extract data from fields
dbf.write(TRAJNUMc=int(str(record.Trajnum)[:4]))
dbf.write(YYYYMMDDc=int(str(record.Trajnum)[-1:] + str(record.Yyyymmdd)[:7]))
dbf.write(TIMEc=record.Yyyymmdd[-1:] + record.Time[:])
db.delete_fields('Trajnum') # delete the incorrect fields
db.delete_fields('Yyyymmdd')
db.delete_fields('Time')
db.delete_fields('1000 201') #delete the unwanted field
db.pack()
But this produces the following error:
dbf.ver_2.BadDataError: record data is not the correct length (should be 31, not 30)
Given the apparent problem that there has been with the txt2dbf conversion, I'm not surprised to find an error in the record data length. However, does this mean that the file is completely corrupted and that I can't extract the information that I need (frustrating because I can see that it exists)?
EDIT:
Rather than attempting to edit the 'bad' .dbf files, it seems a better approach to 1. extract the required data to a text from the bad files and then 2. write to a new dbf. (See Ethan Furman's comments/answer below).
EDIT:
An example of a faulty .dbf file that I need to fix/recover data from can be found here:
https://www.dropbox.com/s/9y92f7m88a8g5y4/p0001120110.dbf?dl=0
An example .txt file from which the faulty dbf files were created can be found here:
https://www.dropbox.com/s/d0f2c0zehsyy8ab/attTEST.txt?dl=0
To fix the data and recreate the original text file, this snippet should help:
import dbf
table = dbf.Table('/path/to/scramble/table.dbf')
with table:
fixed_data = []
for record in table:
# convert to str/bytes while skipping delete flag
data = record._data[1:].tostring()
trajnum = data[:4]
ymd = data[4:12]
time = data [12:16]
level = data[16:].strip()
fixed_data.extend([trajnum, ymd, time, level])
new_file = open('repaired_data.txt', 'w')
for line in fixed_data:
new_file.write(','.join(line) + '\n')
Assuming all your data files look like your sample (the big IF being the data has no embedded commas), then this rough code should help translate your text files into dbfs:
raw_data = open('some_text_file.txt').read().split('\n')
final_table = dbf.Table(
'dest_table.dbf',
'trajnum C(4); yyyymmdd C(8); time C(4); level C(9)',
)
with final_table:
for line in raw_data:
fields = line.split(',')
final_table.append(tuple(fields))
# table has been populated and closed
Of course, you could get fancier and use actual date, and number fields if you want to:
# dbf string becomes
'trajnum N; yyyymmdd D; time C(4), level N'
#appending data loop becomes
for line in raw_data:
trajnum, ymd, time, level = line.split(',')
trajnum = int(trajnum)
ymd = dbf.Date(ymd[:4], ymd[4:6], ymd[6:])
level = int(level)
final_table.append((trajnum, ymd, time, level))

Getting build date and time in RedHat 7.2

I'm trying to add the build date and time to my Qt 5.6 project file, so far I have added:
win32 {
DEFINES += BUILDTIME=\\\"$$system('echo %time%')\\\"
DEFINES += BUILDDATE=\\\"$$system('echo %date%')\\\"
} else {
DEFINES += BUILDTIME=\\\"$$system(date '+%H:%M')\\\"
DEFINES += BUILDDATE=\\\"$$system(date '+%d/%m/%y')\\\"
}
And in the source code:
QString strBuildDT = QString::fromLocal8Bit(BUILDDATE)
+ ", " + QString::fromLocal8Bit(BUILDTIME);
Using this as an example I would get:
12/10/16, 17:39
I would like to reformat the date to display:
12 October 2016, 17:39
From research it looks like the correct date format to use would be:
DEFINES += BUILDDATE=\\\"$$system(date '+%d %B %Y')\\\"
But this doesn't work and returns and empty string for BUILDDATE.
I found a mailing list thread about this. This works (the purpose of $$quote is to prevent Qt from munging spaces, it actually should still produce a non-empty string without $$quote, the real key is the outer \"s)
DEFINES += \"BUILDDATE=\\\"$$quote($$system(date /T))\\\"\"
That works on Windows. I can't test on Linux right now but should be something like:
DEFINES += \"BUILDDATE=\\\"$$quote($$system(date '+%d %B %Y'))\\\"\"
This essentially puts quotes around the whole thing on the compiler command line and lets it work with spaces in the string. Example (Windows, mingw, Qt 4.8.1):
g++ ... -D"BUILDDATE=\"Wed 10/12/2016\"" ...
That said you still may want to just use date '+%s' to get epoch time then format on display with a QDateTime to use the current locale and timezone. Unfortunately, though, I do not know the command to get epoch time on Windows (cursory research does not bode well).
Solution for RedHat:
DEFINES += BUILDDATE=\\\"$$system(date '+%s')\\\"
In code:
QString strBuildDT = QString::fromLocal8Bit(BUILDDATE);
QDateTime qDT = QDateTime::fromMSecsSinceEpoch(strBuildDT.toLong() * 1000);
strBuildDT = qDT.toString("dd MMMM yyyy, HH:mm");
This works well, thank you to https://stackoverflow.com/users/616460/jason-c for the suggestion to try +s

Python/Pandas: How do I convert from datetime64[ns] to datetime

I have a script that processes an Excel file. The department that sends it has a system that generated it, and my script stopped working.
I suddenly got the error Can only use .str accessor with string values, which use np.object_ dtype in pandas for the following line of code:
df['DATE'] = df['Date'].str.replace(r'[^a-zA-Z0-9\._/-]', '')
I checked the type of the date columns in the file from the old system (dtype: object) vs the file from the new system (dtype: datetime64[ns]).
How do I change the date format to something my script will understand?
I saw this answer but my knowledge about date formats isn't this granular.
You can use apply function on the dataframe column to convert the necessary column to String. For example:
df['DATE'] = df['Date'].apply(lambda x: x.strftime('%Y-%m-%d'))
Make sure to import datetime module.
apply() will take each cell at a time for evaluation and apply the formatting as specified in the lambda function.
pd.to_datetime returns a Series of datetime64 dtype, as described here:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html
df['DATE'] = df['Date'].dt.date
or this:
df['Date'].map(datetime.datetime.date)
You can use pd.to_datetime
df['DATE'] = pd.to_datetime(df['DATE'])

TypeError when inserting time into xlsxwriter

I'm importing two points of data from MySQLdb. The second point is a time which cursor.fetchall() returns as a timedelta. I had no luck trying to insert that info into xlsxwriter, always getting a "TypeError: Unknown or unsupported datetime type" error.
Ok... round 2
Now I'm trying to convert the timedelta into a datetime.datetime object:
for x in tempList:
timeString = str(x[1])
ctTime.append(datetime.datetime.strptime(timeString,"%H:%M:%S))
Now in xlsxwriter, I setup formatting:
ctChart.set_x_axis({'name': 'Time', 'name_font': {'size': 14, 'bold': True}, 'num_font': {'italic': True},'date_axis': True})
And then I create a time format:
timeFormat = workbook.add_format({'num_format': 'hh:mm:ss'})
Then I attempt to insert data:
ctWorksheet.write_datetime('A1',ctTime,timeFormat)
But no matter what I do, no matter how I format the data, I always get the following error:
TypeError: Unknown or unsupported datetime type
Is there something stupidly obvious I'm missing?
******* EDIT 1 *******
jmcnamara - In response to your comment here are more details:
I've tried using a list of time deltas such as datetime.timedelta(0, 27453) which when printed is 7:37:33 using the following code:
timeFormat = workbook.add_format({'num_format': 'hh:mm:ss'})
ctWorksheet.write_datetime('A1',ctTime,timeFormat)
I still get the error: TypeError: Unknown or unsupported datetime type
Even iterating through the list and attempting to insert the results fails:
timeFormat = workbook.add_format({'num_format': 'hh:mm:ss'})
i = 0
for t in ctTime:
ctWorksheet.write_datetime(i,0,t,timeFormat)
i += 1
I finally got it working with my most recent code. The chart still isn't graphing correctly using the inserted times, but at least they are inserting correctly.
Since I was pulling the timedeltas from SQL, I had to change their format first. Raw timedeltas from SQL just weren't working:
for x in templist:
timeString = datetime.datetime.strptime(str(x[1]),"%H:%M:%S")
ctTime.append(timeString)
With those datetime.strptime formatted times I was able to then successfully insert into the worksheet.
timeFormat = workbook.add_format({'num_format': 'hh:mm:ss'})
i = 0
for t in ctTime:
ctWorksheet.write_datetime(i,0,t,timeFormat)
i += 1
The GitHub master version of XlsxWriter supports datetime.timedelta.
Try it out and let me know if it works. It will probably be uploaded to PyPI in the next week.