python - Python27 - Convert tuple time to datetime object -


i'm trying timestamp email this:

received: 10.64.149.4 smtp id tw4csp1211013ieb;     thu, 4 aug 2016 07:02:01 -0700 (pdt) 

first of all, parse timestamp with:

d = email.utils.parsedate('thu, 4 aug 2016 07:02:01 -0700 (pdt)')  result: (2016, 8, 4, 7, 2, 1, 0, 1, -1) 

here comes problem. try convert result datetime, in vain.

d = email.utils.parsedate('thu, 4 aug 2016 07:02:01 -0700 (pdt)')  date_object = datetime(d)  result: traceback (most recent call last):   file "data.py", line 12, in <module>     date_object = datetime(d) typeerror: integer required 

what's problem?

email.utils.parsedate returns 9 tuple similar structure struct_time index 6,7 , 8 unusable

struct_time:

index   attribute   values 0       tm_year     (for example, 1993) 1       tm_mon      range [1, 12] 2       tm_mday     range [1, 31] 3       tm_hour     range [0, 23] 4       tm_min      range [0, 59] 5       tm_sec      range [0, 61]; see (2) in strftime() description 6       tm_wday     range [0, 6], monday 0 7       tm_yday     range [1, 366] 8       tm_isdst    0, 1 or -1 

and datetime objects require different values constructor

datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])

you directly create datetime using useful parts of tuple as

date_object = datetime(*d[0:6])


edit: careful this, because create object in local time, disregarding time zone information.


edit 2: can solve using strptime, need cut (pdt) end of string, since pdt not valid name tzinfo, -0700 enough


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -