how do I convert str postfixed with 'Z' to dateTime structure? - rust

According to this RFC, sent_time is in ISO 8601 UTC format. Based on that info I should be able to use DateTime::parse_from_rfc3339 to parse sent_time into a DateTime struct, per the docs.
However, using the value of sent_time in the example in the RFC, I get an error. This line of code
let dt = DateTime::parse_from_rfc3339("2019-01-15 18:42:01Z").unwrap_err();
Produces this output if I println! it
`"input contains invalid characters"`
I have tried using both DateTime::parse_from_str and NaiveDateTime::parse_from_str, both of which return the same error: eg this line of code
let dt = NaiveDateTime::parse_from_str("2019-01-15 18:42:01Z", "%Y-%m-%d %H:%M:%S").unwrap_err();
produces if I println! it
"trailing input"
I do not see any documentation about DateTime string formatting which allows for time to formatted like the example above. Perhaps I have missed reading it.
If I have understood the wiki page correct, sent_time example is correctly formatted date time string. Does this seem accurate?
If so, how can I parse it to DateTime struct?

NaiveDateTime with format %Y-%m-%d %H:%M:%SZ works, notice you need to add the literal Z at the end of format to match your string:
let dt = NaiveDateTime::parse_from_str("2019-01-15 18:42:01Z", "%Y-%m-%d %H:%M:%SZ");
println!("{:?}", dt);
// Ok(2019-01-15T18:42:01)
Playground.

Related

Why does this python datetime format not convert the string of the same format into a datetime object successfully?

import datetime as dt
time_str = '2022-02-25 18:37:46.594385+00:00'
Then I try to convert this into a datetime object as follows:
dt.datetime.strptime(time_str,'%Y-%m-%d %H:%M:%S.%f%z')
However it results in the following error:
ValueError: time data '2022-02-25 18:37:46.594385+00:00' does not match format '%Y-%m-%d %H:%M:%S.%f%z'
The error appears to be coming from the %z section of the format, but overall I do not understand why this is not working, since it seems the specified format does match the string format. If you could help identify any issues and suggest a solution to convert the example time_str into a datetime object successfully. Thanks!

Convert string to datetime in local timezone Python

I have datetime in string needing to be converted in datetime format. Below is my code but it returns error. what I am missing here.
from datetime import datetime
LocalStartTime='2020-09-17T10:55:06.4000000+1000'
datetime_object = datetime.strptime(LocalStartTime, '%Y-%m-%dT%H:%M:%S.%f%z')
Required output shd be date converted in current timezone to format like: '2020-09-17 20:55:06' whatever will be the actual value.
returns below error:
ValueError: time data '2020-09-17T10:55:06.4000000+1000' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'
from datetime documentation:
When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right. %f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available).
you have one too many zeros in the float part after the seconds part.
the limitation is 6 digits.
from datetime import datetime
LocalStartTime='2020-09-17T10:55:06.400000+1000'
datetime_object = datetime.strptime(LocalStartTime, '%Y-%m-%dT%H:%M:%S.%f%z')
should work
Edit:
after the OP edited and asked about converting to a different timestamp:
seems like what you're looking for is timestamp() and fromtimestamp()
you can get the timestamp which is a posix timestamp represented as float, and convert it back to datetime object with fromtimestamp() if you want to remove the float part after the seconds you can convert the time stamp to int.
datetime.fromtimestamp(int(datetime_object.timestamp()))

How do I see a user-friendly format when debugging chrono::DateTime in vscode-lldb?

The debugger shows this for DateTime structs:
After looking at the docs for lldb to see how to format it, I see I can format integers as hex:
type format add -f hex i32
I tried something similar for DateTime
type format add --format hex chrono::datetime::DateTime<chrono::offset::utc::Utc>
It's not picking up the chrono type even though frame variable shows this as the type. Even after this step is done, not sure how to parse the date to string.
Using #Jim Ingham hints in the other answer and a touchup to this formula
Modify the launch.json file by adding
"initCommands": [
"command source '${workspaceFolder}/my_type_formatters'"
]
Add the following file called my_type_formatters to the root of the project.
command script import simd.py
type summary add -F simd.GetSummary chrono::datetime::DateTime<chrono::offset::utc::Utc>
Add a simd.py file to the root of the project with:
from datetime import datetime,timedelta
def GetSummary(valobj, internal_dict):
ymdf = valobj.GetChildMemberWithName('datetime').GetChildMemberWithName('date').GetChildMemberWithName('ymdf').GetValue();
secs = valobj.GetChildMemberWithName('datetime').GetChildMemberWithName('time').GetChildMemberWithName('secs').GetValue();
year = int(ymdf) >> 13
day_of_year = (int(ymdf) & 8191) >> 4;
date = datetime(year -1, 12, 31) + timedelta(days=day_of_year) + timedelta(seconds=int(secs))
return date.strftime('%Y-%m-%d %H:%M:%S')
Result:
lldb has three stages of customization for printing values of a given type. The simplest is "type format" which specifies the format to use (hex, chars, etc) to display scalar entities. The second is "type summary" which allows you to print a one-line string summary of the value. The third is "type synthetic" which allows you to present a value as some kind of structured object (e.g. making std::vector look like an vector of values rather than its internal form.)
You want to add a "type summary" for this type that parses the data and prints it as a human-readable string.

Convert number to datetime format

How do I Convert "1561994754" number to "2019-07-01T15:25:54.000000"
I have used :
import datetime
datetime.datetime.fromtimestamp(x['date'] / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f')
But I am getting 1970-01-18 19:53:14.754000, can you please guide me to correct function?
Thanks,
Aditya
Removing the / 1000 gives me '2019-07-01 08:25:54.000000', It seems like there was a unit mismatch in your expression. To exactly match the format you're asking for, datetime.datetime.fromtimestamp(x['date'], tz=datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f') produces '2019-07-01T15:25:54.000000 (leaving the timezone argument blank defaults to using local time, but the human-readable date in your question uses UTC)
You can try like this!
String myString = String.valueOf(1561994754);
DateFormat format = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ssZ");
Date date = format.parse(myString);

datetime.strptime with local time zone

I have in a dataframe a column time in UTC time, and I want to convert it in local time. I did this code:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')
utc = utc.replace(tzinfo=from_zone)
# Convert time zone
central = utc.astimezone(to_zone)
Then I save it in a text file in a string.
So the string has this format:
2011-01-21 02:37:21+02:00
Then I load the text file in another program and I want to convert it in datetime format with local time zone
So I tried to use datetime.strptime() with the %Z parameter :
datetime.strptime(central,'%Y-%m-%d %H:%M:%S.%f Paris, Madrid')
Paris, Madrid is what the command datetime.tzname(central) gave me.
It is not working and I didn't find any explanations on how to use %Z.
If you have any explanations, please help me.
The datetime.strptime() function works a bit differently than this.
The first argument is the string with the time info, and the second argument is some type of formatting to it that allows the function to translate the string to a datetime object.
'.%f Paris, Madrid' is making the function think these words appear in the string, so an error will rise when the formatting and the string do not match.
The correct code would be:
datetime.strptime(central,'%Y-%m-%d %H:%M:%S%z')

Resources