Given a string as below, I need to convert:
1 Dec 2008 06:43:00 +0100
to
MM/DD/YYYY HH:MM:SSAM
using jython what is the best way to do this?
I don't have jython handy, but I'd expect something like this to work:
import java
sdf = java.text.SimpleDateFormat
fmt_in = sdf('d MMM yyyy HH:mm:ss Z')
fmt_out = sdf('MM/dd/yyyy HH:mm:ssaa')
fmt_out.format(fmt_in.parse(time_str))
Jython 2.5b0 (beta) has an implementation of the time module that includes
strptime(string[, format]).
Parse a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().
(strptime is missing in Jython2.2.1).
A python version of the conversion formats will look like (not sure of the zone component):
import time
mytime = time.strptime("1 Dec 2008 06:43:00 +0100", "%d %b %Y %H:%M:%S %Z")
new_time_string = time.strftime("%m/%d/%Y %I:%M:%S%p", mytime)
Related
This is the data that is being returned from my API:
"Jun 02, 2021, 2 PMEST"
If I'm within 7 days of the current date which I'm getting by doing this:
from datetime import date
today = date.today()
print("Today's date:", today)
Just need to convert Jun to a number and 02 and compare to see if it's within 7 days in the future of the current date, then return True
APPROACH 0:
Given the format of your example data, you should be able to convert it to a datetime using this code:
datetime.strptime("Jun 02, 2021, 2 PMEST", "%b %d, %Y, %I %p%Z")
The details about this format string are here: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
However, when I tested this locally, it worked for this input:
"Jun 02, 2021, 2 PMUTC"
but not for your input (which has different timezone):
"Jun 02, 2021, 2 PMEST"
I have investigated this some more and "read the docs" (https://docs.python.org/3/library/time.html).
To get EST parsing to work, you would have to change your OS timezone and reset the time module's timezones like this:
from datetime import datetime
import os
import time
os.environ["TZ"] = "US/Eastern". # change timezone
time.tzset(). # reset time.tzname tuple
datetime.strptime("Jun 02, 2021, 2 PMEST", "%b %d, %Y, %I %p%Z")
When you're done, be safe and delete the "hacked" environment variable:
del os.environ["TZ"]
Note - Since your system timezone is presumably still UTC, it can still parse UTC timezone too.
See this thread for detailed discussion: https://bugs.python.org/issue22377
Also note that the timestamp is not actually captured. The result you get with EST and UTC is a naive datetime object.
APPROACH 1
So, it seems like there is a better way to approach this.
First, you need to pip install dateutils if you don't already have it.
THen do something like this:
from dateutil import parser
from dateutil.tz import gettz
tzinfos = {"EST": gettz("US/Eastern")}
my_datetime = parser.parse("Jun 02, 2021, 2 PM EST", tzinfos=tzinfos)
What's happening here is we use gettz to get timezone information from the timezones listed in usr/share/zoneinfo. Then the parse function can (fuzzy) parse your string (no format needs to be specified!) and returns my_datetime which has timezone information on it. Here are the parser docs: https://dateutil.readthedocs.io/en/stable/parser.html
I don't know how many different timezones you need to deal with so the rest is up to you. Good luck.
Convert the date to a datetime structure and take the direct difference. Note that today must be a datetime, too.
import datetime
date_string = "Jun 02, 2021, 2 PMEST"
today = datetime.datetime.today()
date = datetime.datetime.strptime(date_string,
"%b %d, %Y, %I %p%Z") # Corrected
(date - today).days
#340
In my python code I get start and end time some thing like:
end = int(time.time())
start = end - 1800
Now start and end variables holds values like 1460420758 and 1460422558.
I am trying to convert it in a meaningful format like :
Mon Apr 11 17:50:25 PDT 2016
But am unable to do so, I tried:
time.strftime("%a %b %d %H:%M:%S %Y", time.gmtime(start))
Gives me
Tue Apr 12 00:25:58 2016
But not only the timezone but the H:M:S are wrong
As date returns me the below information:
$ date
Mon Apr 11 18:06:27 PDT 2016
How to correct it?
This one involves utilizing datetime to great the format you wish with the strftime module.
What's important is that the time information you get 'MUST' be UTC in order to do this. Otherwise, you're doomed D:
I'm using timedelta to 'add' hours to the time. It will also increments the date, too. I still would recommend using the module I shared above to handle time zones.
import time
# import datetime so you could play with time
import datetime
print int(time.time())
date = time.gmtime(1460420758)
# Transform time into datetime
new_date = datetime.datetime(*date[:6])
new_date = new_date + datetime.timedelta(hours=8)
# Utilize datetime's strftime and manipulate it to what you want
print new_date.strftime('%a %b %d %X PDT %Y')
how would i convert this timestamp '20141031131429Z' to 31 october 2014 in python
>>>datetime.datetime.strptime( "20141031131429Z", "%Y%m%d%H%M%S%Z" )
the above code gives me an error shown below:
ValueError: time data '20141031131429Z' does not match format '%Y%m%d%H%M%S%Z'
Remove the % in front of the Z:
d = datetime.datetime.strptime("20141031131429Z", "%Y%m%d%H%M%SZ" )
print(d.strftime("%d %B %Y"))
Output:
31 October 2014
Set the documentation for the strftime() and strptime() behavior.
That's not a unix timestamp (which are parsed with %s in strftime/strptime) - it looks like iCalendar form #2 (RFC 2445). A module like iCalendar might help you parse that without having to hardcode which form is used.
Once you have a datetime object, it can be used to retrieve any other format:
>>> dt=datetime.datetime.strptime( "20141031131429Z", "%Y%m%d%H%M%SZ" )
>>> dt.strftime('%d %B %Y')
'31 October 2014'
>>> dt.strftime('%x')
'10/31/14'
A variety of programs output date formats according to the syntax of their Unix platforms date command. For example: Tue Nov 5 12:38:00 EST 2013.
How can I easily convert this into a Python date object?
The answer is actually pretty simple. You just need to use the datetime.strptime() method which converts a string representation of a date (1st parameter) into a date object based on a directive which specifies that format of the string representation (2nd parameter).
In this case, this is the code you would use:
import datetime
unix_date_format = '%a %b %d %H:%M:%S %Z %Y'
# Matches strings like Tue Nov 5 12:38:00 EST 2013
my_date = datetime.datetime.strptime(
date_in_string_format, unix_date_format)
Further Reading
datetime.strptime() method
I'm using Python 3.3. I'm getting an email from an IMAP server, then converting it to an instance of an email from the standard email library.
I do this:
message.get("date")
Which gives me this for example:
Wed, 23 Jan 2011 12:03:11 -0700
I want to convert this to something I can put into time.strftime() so I can format it nicely. I want the result in local time, not UTC.
There are so many functions, deprecated approaches and side cases, not sure what is the modern route to take?
Something like this?
>>> import time
>>> s = "Wed, 23 Jan 2011 12:03:11 -0700"
>>> newtime = time.strptime(s, '%a, %d %b %Y %H:%M:%S -0700')
>>> print(time.strftime('Two years ago was %Y', newtime))
Two years ago was 2011 # Or whatever output you wish to receive.
I use python-dateutil for parsing datetime strings. Function parse from this library is very handy for this kind of task
Do this:
import email, email.utils, datetime, time
def dtFormat(s):
dt = email.utils.parsedate_tz(s)
dt = email.utils.mktime_tz(dt)
dt = datetime.datetime.fromtimestamp(dt)
dt = dt.timetuple()
return dt
then this:
s = message.get("date") # e.g. "Wed, 23 Jan 2011 12:03:11 -0700"
print(time.strftime("%Y-%m-%d-%H-%M-%S", dtFormat(s)))
gives this:
2011-01-23-21-03-11