I'm currently trying to writing a script to automate a function at work, but I'm not intimately familiar with Python. I'm trying to take a XML dump and compare a specific entry's date to see if the time has passed or not.
The date is in a particular format, given:
<3-letter Month> <DD> <HH:MM:SS> <YYYY> <3-letter Timezone>
For example:
May 14 20:11:20 2014 GMT
I've parsed out a string in that raw form, and need to somehow compare it with the current time to find out if the time has passed or not. That said, I'm having a bit of trouble figuring out how I should go about either formatting my text, or choosing the right mask/time format in Python.
I've been messing around with different variations of the same basic format:
if(trimmed < time.strftime("%x") ):
Trimmed is the clean date/time string. Time is derived from import time.
Is there a simple way to fix this or will I have to dig into converting the format etc.? I know the above attempt is simplistic, but I'm still very new to Python. Thanks for your time and patience!
You should use combination of gmtime (for GMT time),mktime and datetime.
from time import gmtime,mktime
from datetime import datetime
s = "May 14 20:11:20 2014 GMT"
f = "%b %d %H:%M:%S %Y GMT"
dt = datetime.strptime(s, f)
gmt = datetime.fromtimestamp(mktime(gmtime()))
if dt<gmt:
print(dt)
else:
print(gmt)
Related
I need to get time in python and i am using time.ctime() and it returns this Thu Jul 8 15:37:26 2021
But i only need 15:37:26 and i cant figure out how to get only this and not the date and year.
I already tried using datetime where i could not figure it out either so im trying with time now.
here is a bit of code for the context:
cas = time.ctime()
cas = str(cas)
api.update_status('nyni je:'+ cas )
time.sleep(60)
Anyone know how to do it?
print(datetime.datetime.now().time().isoformat(timespec='seconds'))
import datetime
print(datetime.datetime.now().strftime("%H:%M:%S"))
imports
from datetime import datetime
code
now = datetime.now()
cas = now.strftime("%H:%M:%S")
print(cas)
You can use strftime to convert a datetime value to a string of a certain format. In your case you can use %H:%M:%S to only get the time. The same function can be used to get the date as well, you can read more here.
Take a look at the "strftime() and strptime() Format Codes" section also for how you can format it.
I am downloading a json file containing timestamp using python . But the timestamp i am getting is below format
`2021-04-01T21:43:52.757Z`
Want to convert into normal timestamp (CST Hrs). I also see that the time is increased by 4 hours when i compare the report manually.
`4/1/2021 5:43:53 PM`
The above hours is 4 hrs less when i compare with json file entry. Please advise me.
You need to use python's datetime module to handle this. The Z in the string actually means time zone 0 or UTC time which is 6 hours ahead of CST not 4:
import datetime
date_object = datetime.datetime.strptime(
"2021-04-01T21:43:52.757Z", "%Y-%m-%dT%H:%M:%S.%fZ"
)
date_object = date_object - datetime.timedelta(hours=6)
print(
f"{date_object.month}/{date_object.day}/{date_object.year} {date_object.strftime('%I:%M:%S %p')}"
)
Which will give this output:
4/1/2021 03:43:52 PM
have to use an f string if you want non zero padded dates because its not available in datetime according to the docs
You can use pytz module to deal with time zones directly and not hardcode them if you want. Or if you are on python 3.9 you can use timezone objects to create timezones yourself
I'm trying to change the datetime format from "2019-02-08 15:00" to "8 feb", but the hour and minute seems to stop me from doing this in an easy way.
The variable containing this info is my_task['due']['string'] and if I print it I get "2019-02-08 15:00".
Then I run this code:
variabel = time.strftime('%d %b', my_task['due']['string'])
But I am getting the error:
TypeError: argument must be sequence of length 9, not 16
In PHP, which I'm quite good at, this is easy peasy, but I'm guessing I'm missing some small detail here. Can someone please give me a push in the right direction?
Appears that you are working with datetime strings and not datetime objects, so you will first need to create a datetime object from your string in order to use datetime.strftime() to reformat it.
Also note that datetime objects and time objects are not the same despite sharing some common methods.
For example:
from datetime import datetime
formatted = datetime.strptime('2019-02-08 15:00', '%Y-%m-%d %H:%M').strftime('%d %b')
print(formatted)
# OUTPUT
# 08 Feb
I am somewhat new to Python and have a seemingly simple question.
I have a python script that interacts with an API (RHN Satellite if you're curious). This API returns a date in the form of a string and it always trims leading 0's. For example, 6/1/13 or 10/9/12. I need to convert this string to a date and determine the day of the year it is.
Here is what I know:
today = datetime.datetime.now()
print today.strftime('%j')
...will return today's day of year (175). This works fine for a datetime object but I am having trouble converting the string given by the API to an actual date. If I use:
date = datetime.datetime.strptime(var, '%m/%d/$y')
I get error:
ValueError: time data '5/2/13' does not match format '%m/%d/$y'
I'm guessing because it's expecting leading 0's ? How do I get around this?
In the end, I am trying to subtract the variable date given from the current date but I can't do that until I convert the string.
Thanks for the help!
I think you just have a typo, use %y instead of $y:
date = datetime.datetime.strptime(var, '%m/%d/%y')
This code works for me, provided you change $y to %y in the format code.
Correct the $y to %y and I'd use format instead of strftime:
from datetime import datetime
print format(datetime.strptime('5/2/13', '%m/%d/%y'), '%j')
I am new to python and i have written a script that converts a string date coming in to a datetime format going out. My problem is that cannot convert the datetime object back to a string for manipulation. i have a date eg 2011-08-10 14:50:10 all i need to to is add a T between the date and time and a Z at the end. unfortunately im using python 2.3 as my application will only accept that.
my code is as follows:
fromValue= ''
fromValue = document.Get(self._generic3)
fromValue = fromValue[:fromValue.rindex(" ")]
fromValue = datetime.datetime.fromtimestamp(time.mktime(time.strptime(fromValue,"%a, %d %b %Y %H:%M:%S")))
toValue = fromValue.strftime("%Y-%m-%dT %H:%M:%SZ")
This should work fine. datetime.strftime was available on Python 2.3.
You'd certainly be better off upgrading to at least Python 2.5 if at all possible. Python 2.3 hasn't even received security patches in years.
Edit: Also, you don't need to initialize or declare variables in Python; the fromValue= '' has no effect on your program.
Edit 2: In a comment, you seem to have said you have it in a string already in nearly the right format:
"2011-08-08 14:15:21"
so just do
'T'.join("2011-08-08 14:15:21".split()) + 'Z'
If you want to add the letters while it's a string.
It looks like you are trying to format the datetime in ISO-8601 format.
For this purpose, use the isoformat method.
import datetime as dt
try:
import email.utils as eu
except ImportError:
import email.Utils as eu # for Python 2.3
date_string="Fri, 08 Aug 2011 14:15:10 -0400"
ttuple=eu.parsedate(date_string)
date=dt.datetime(*ttuple[:6])
print(date.isoformat()+'Z')
yields
2011-08-08T14:15:10Z
Here is link to isoformat and parsedate in the Python2.3 docs.
fromValue.strftime('%Y-%m-%d T %H:%M:%S Z')
http://docs.python.org/release/2.3/lib/module-time.html
http://docs.python.org/release/2.3/lib/node208.html