datetime.strptime with local time zone - python-3.x

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')

Related

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 convert str postfixed with 'Z' to dateTime structure?

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.

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);

How can i format date in groovy script

Hi I have a date format that i am getting from my Jira Sprint Environment 2019-03-29T06:56:00.000-04:00
I am using groovy Script.
I have tried to use multiple format to make similar format like the above .
But Unable to do it.
Here are the below solution i have tried.
1 --
`def sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
sdf.setTimeZone(TimeZone.getTimeZone("GMT"))
log.debug("Printing Current time stamp date : "+sdf)
solution 1 is printing text only.
2 --
def now = new Date()
println now.format("yyyy-MM-dd'T'HH:mm:ss'Z'",TimeZone.getTimeZone('UTC'))
this one is printing
Printing Current time stamp date : Thu Sep 26 08:00:35 EDT 2019"
Can anyone help me on this?
So, the goal is to have date in format
2019-03-29T06:56:00.000-04:00
the following code does the formatting with timezone GMT-4
def now=new Date().format("yyyy-MM-dd'T'HH:mm:ss.SSSXXX",TimeZone.getTimeZone('GMT-4'))
println now
prints
2019-09-26T16:33:18.462-04:00
note that the variable now will contain String with formatted date
Check for all available date & time patterns:
https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html
Given that you’ve got a Java 8 or newer underneath, all you need is
OffsetDateTime.now(ZoneId.systemDefault()).toString()
In my time zone (Europe/Copenhagen) I just got
2019-09-27T21:46:53.336204+02:00
If your default time zone is America/Montreal or America/New_York, you will get the time at offset -04:00 as long as summer time (Daylight Saving Time) is in effect, then -05:00.
And you can easily parse.
OffsetDateTime.parse( "2019-09-27T21:46:53.336204+02:00" )
See this code running at IdeOne.com.
def currentDate = new Date()
def date = currentDate.format('yyyy-MM-dd')
def time = currentDate.format('HH:mm:ss.SSS')
def dateTime = date.toString() + 'T' + time.toString() + 'Z'

Convert date string to timestamp, groovy

I have a date string as follows:
201805041235040000000
Which I would like to convert to timestamp with zone in Groovy.
Tried this:
def timestamp = Date.parse("yyyyMMddHHmmss", timstamp).format("yyyy-MM-dd'T'HH:mm:ssZ");
But failed, got error:
No signature of method: static java.util.Date.parse() is applicable for argument types.
Let me know where am I going wrong.
Try this:
String t2,st = "16/08/2007 09:04:34"
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss")
Date date = sdf.parse(st)
Timestamp timestamp = new Timestamp(date.getTime())
t2 = timestamp.toString()
Hope it helps....
This works...
String input = '201805041235040000000'
String timestamp = Date.parse('yyyyMMddHHmmss', input).format("yyyy-MM-dd'T'HH:mm:ssZ")
It is a bit unclear what you are looking for. If you just need a time stamp from parsing your date string, you can use the groovy extension Date.toTimestamp():
def ts = Date.parse("yyyyMMddHHmmssSSS", "201805041235040000000".take(17)).toTimestamp()
where the take(17) is there to discard any trailing zeros not included in the date pattern yyyyMMddHHmmssSSS. I made the assumption that three of the tailing zeros were milliseconds. If that's not the case:
def ts = Date.parse("yyyyMMddHHmmss", "201805041235040000000".take(14)).toTimestamp()
what is unclear is what you mean when you say "with zone". So assuming you just want to include the current time zone information and generate a String, I don't see a reason why you should convert from date to timestamp in the first place (Timestamp after all is a Date as it inherits from Date). If you just need the timezone spelled out you can do:
def withZone = Date.parse("yyyyMMddHHmmss", "201805041235040000000".take(14)).format("yyyy-MM-dd'T'HH:mm:ssZ")
println withZone
which on my machine where I'm sitting in Sweden prints out:
~> groovy withTimeZone.groovy
2018-05-04T12:35:04+0200
timestamp must be string. Try this:
Date.parse("yyyyMMddHHmmss", timstamp?.toString()[0..13])
.format("yyyy-MM-dd'T'HH:mm:ssZ")

Resources