format error in python string to time conversion~ - python

Currently, test 32 is the str type.
I would like to express the str type of test32 in time data. yyyy-mm-dd hh:mm:ss method...
However, time data '22/03/0823:33:55.256' does not match format '%Y%m%d%H%M%S' error occurs. Is there any way?
for z in data:
if 'D:\System\iUTILITY\Tool\Curver\ToolBox\STG\i02-K01_S1_CEC_Update_Monintor_Analysis.xpsp' in z:
test30 = z.split(' ')[0:2]
test31 = ''.join(test30)
test32 = test31.split(',')[0]
print(type(test32))
test33 = datetime.datetime.strptime(test32, '%Y%m%d%H%M%S')
print(test33)
# print(test32)

To parse the date 22/03/0823:33:55.256, you need to use format %y/%m/%d%H:%M:%S.%f, like this:
datetime.datetime.strptime('22/03/0823:33:55.256', '%y/%m/%d%H:%M:%S.%f')
# Ouptut: datetime.datetime(2022, 3, 8, 23, 33, 55, 256000)
According to the document, %y stands for the year without century, and %f stands for the microsecond. Here's the document:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

Related

pdf.getDocumentInfo date format

I am using pypdf2's function for extracting document info. The results are something like this but I am unable to interpret the creation date format. What are the last few digits representing?
pdf.documentInfo
[Output]: {'/Creator': 'Rave (http://www.nevrona.com/rave)',
'/Producer': 'Nevrona Designs',
'/CreationDate': 'D:20060301072826' }
and at one point I also saw this:
CreationDate': "D:20170920114835+02'00'"
how can I read or convert it into a normal date time readable format?
you can clean & parse like
from datetime import datetime
CreationDate = "D:20170920114835+02'00'"
dt = datetime.strptime(CreationDate.replace("'", ""), "D:%Y%m%d%H%M%S%z")
# UTC offset is set correctly:
print(dt)
# 2017-09-20 11:48:35+02:00
print(repr(dt))
# datetime.datetime(2017, 9, 20, 11, 48, 35, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200)))
...which I think is more straight forward than the answer to this related question shows.

How to convert `2020-04-06T09:04:52.610+02:00` into a `datetime.datetime` in Python3?

How to convert 2020-04-06T09:04:52.610+02:00 into a datetime.datetime in Python3?
I know that strptime is used to convert a str into a datetime, whereas strftime is used to convert a datetime into a str.
There are many examples online, like datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p').
My problem is the following part of the time above: T09:04:52.610+02:00. I can't find any sensible format code on http://strftime.org/ that matches it.
If I had a matching format code, I would write something like:
datetime.strptime('2020-04-06T09:04:52.610+02:00', '%Y-%m-%d%X'), where %X would match the T09:04:52.610+02:00 part.
It's a date formatted as ISO format, so just go ahead and use datetime.fromisoformat:
>>> import datetime as dt
>>> dt.datetime.fromisoformat("2020-04-06T09:04:52.610+02:00")
datetime.datetime(2020, 4, 6, 9, 4, 52, 610000, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200)))
As for strptime, the second argument is basically any string with some special markers in it (like %b). You can perfectly include any characters you want in that string, so the following works as well (although fromisoformat is obviously the way to go):
>>> dt.datetime.strptime("2020-04-06T09:04:52.610+02:00", "%Y-%m-%dT%H:%M:%S.%f%z")
datetime.datetime(2020, 4, 6, 9, 4, 52, 610000, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200)))

What is the difference between strptime and strftime?

I am working on a project , where I have dictionary with column date called "starttime" .. I need to extract month , hour and year , day of the week.
I am stuck for now I have the below code .
{if city =='NYC':
datn = datum[('starttime')]
datn = dt.strptime(datn,"%m/%d/%y %H:%M:%S")
hour = dt.strftime(datn,"%H")
year = dt.strftime(datn,"%y")
elif city == 'Chicago':
datc = datum[('starttime')]
datc = dt.strptime(datc,"%m/%d/%y %H:%M")
month = dt.strftime(datc,"%m")
hour = dt.strftime(datc,"%H")
year = dt.strftime(datc,"%y")
else:
datw = datum[('start date')]
datw = dt.strftime (datw,"%m")
hour = dt.strftime(datw,"%H")
year = dt.strftime(datw,"%y")
return (month, hour, day_of_week)
}
my import statements are on the top of my code , as below:
from datetime import datetime
strptime translates to
"parse (convert) string to datetime object."
strftime translates to
"create formatted string for given time/date/datetime object according to specified format."
Why do you need strftime?
This is what a datetime object looks like: (2015, 7, 19, 22, 7, 44,
377000)
To someone who isn't quite familiar with this format, with the
exception of the year, what's written up there is not immediately
intuitive. So you probably would be better off with something like
Sun, 19 July, 2015. That's what strftime is used for. You simply need
to learn the proper formatting strings.
One Good Link over SO read about this !
strptime converts the string to a datetime object.
strftime creates a formatted string for given time/date/datetime object according to specified format by the user
you would use strftime to convert a datetime object like this: datetime (2018, 10, 20, 10, 9, 22, 120401) to a more readable format like "20-10-2018" or 20th of October 2018.

I want to parse string to timestamp-with-timezone in python

I try to parse string to time-stamp with timezone format.
here is an example
"2016-02-18 16:13:07+09"
i want to know parsing this string format to time-stamp format in python.
how can i do that?
Is the UTC offset format in your string +09 or +0900 ?
If the offset in your string is 0900 you can use the below .If your UTC offset is only +09 as you mentioned in your question , you can pad the string with 00 and get the below code to work .
Code:
import datetime
time="2016-02-18 16:13:07+0900"
new_time=datetime.datetime.strptime(time,"%Y-%m-%d %H:%M:%S%z")
print(new_time)
new_time_python=datetime.datetime.strftime(new_time,"%m-%d-%y")
print(new_time_python)
Output
2016-02-18 16:13:07+09:00
02-18-16
dateutil might be a suitable library for your purposes:
from dateutil.parser import parser
p = parser()
d = p.parse('2016-02-18 16:13:07+09'.decode('utf-8')) # must be unicode string
d
>>> datetime.datetime(2016, 2, 18, 16, 13, 7, tzinfo=tzoffset(None, 32400))
If the UTC offset may be specified both as +HH and +HHMM format then you could use str.ljust() method to normalize the input time string. Then you could use .strptime() to parse it:
#!/usr/bin/env python3
from datetime import datetime
time_string = "2016-02-18 16:13:07+09"
dt = datetime.strptime(time_string.ljust(24, "0"), "%Y-%m-%d %H:%M:%S%z")
# -> datetime.datetime(2016, 2, 18, 16, 13, 7,
# tzinfo=datetime.timezone(datetime.timedelta(0, 32400)))
If your Python version doesn't support %z, see How to parse dates with -0400 timezone string in python?

Get Unix date (numeric) from string and convert to Python date

I'm trying to extract a unix date from a rather large body of text returned on a url link so Ive used:
link = Open_URL(url)
match=re.compile('"Date":"(.+?)"').findall(link)
But when I print the unix date its a large number rather than a date, I need to convert it to a usable date format, I tried:
datetime.fromtimestamp(int(my)ints)).strftime('%Y-%m-%d %H:%M:%S')
But it wont allow me to convert a link, any ideas?
Thanks in advance
Current code:
link = Open_URL(url)
match=re.compile('"End Date":"(.+?)"').findall(link)
for url in match:
So on
Please help I'm stuck! cannot do anything with the list it returns except print it, which is useless in its current format
Thanks
If your match variable looks like ['1448204858'] when printed then it is a list containing a single string element. datetime.fromtimestamp() requires a float value, so you need to
extract the string from the list,
convert it to a float, and then
convert that to a datetime:
import re
from datetime import datetime
# test data
link = '"Something":"foo","Date":"1448204858","Otherthing":"bar"'
match=re.compile('"Date":"(.+?)"').findall(link)
dt = datetime.fromtimestamp(float(match[0]))
print(repr(dt))
print(dt.strftime('%Y-%m-%d %H:%M:%S'))
Results:
datetime.datetime(2015, 11, 22, 8, 7, 38)
2015-11-22 08:07:38
I think what you mean by a large number is UNIX time stamp also known as time since epoch. It can be easily converted to a datetime object in python as so:
import datetime
a = datetime.datetime.timestamp(datetime.datetime.now())
print(a) # 1448206588.806814
b = datetime.datetime.fromtimestamp(a)
print(b) # datetime.datetime(2015, 11, 22, 21, 7, 8, 661906)
# using strftime on above object
print(b.strftime('%Y-%m-%d %H:%M:%S')) #'2015-11-22 21:07:08'

Categories