How do you convert a time.struct_time object into a datetime object?
Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.
from datetime import datetime
from time import mktime
dt = datetime.fromtimestamp(mktime(struct))
Converting time_struct with timezone to datetime GMT in Python
to get a time zone aware datetime object, you could unpack the relevant part of the timetuple into a datetime object and set the tzinfo attribute to UTC:
from datetime import datetime, timezone
# given a time_struct tuple like
s = (2020, 9, 6, 23, 7, 16, 6, 250, 0)
# convert to datetime object as
dt = datetime(*s[:6], tzinfo=timezone.utc)
print(dt)
>>> 2020-09-06 23:07:16+00:00
How do you convert a python time.struct_time object into a ISO string?
Using time.strftime()
is perhaps easiest:
iso = time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)
Demo:
>>> import time
>>> timetup = time.gmtime()
>>> time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)
'2013-10-11T13:31:03Z'
You can also use a datetime.datetime()
object, which has a datetime.isoformat()
method:
>>> from datetime import datetime
>>> datetime(*timetup[:6]).isoformat()
'2013-10-11T13:31:03'
This misses the timezone Z
marker; you could just add that.
How do I convert a datetime.date object into a time.struct_time object?
Try using date.timetuple()
. From the Python docs:
Return a
time.struct_time
such as
returned bytime.localtime()
. The
hours, minutes and seconds are 0, and
the DST flag is -1.d.timetuple()
is
equivalent to
time.struct_time((d.year, d.month,
, where
d.day, 0, 0, 0, d.weekday(), yday,
-1))yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1
is
the day number within the current year
starting with 1 for January 1st.
How to *change* a struct_time object?
Use the datetime
module instead, which has a far richer set of objects to handle date(time) arithmetic:
import datetime
adate = datetime.datetime.strptime("23.10.2012", "%d.%m.%Y").date()
adate + datetime.timedelta(days=30)
You can use the excellent python-dateutil
add-on module to get an ever richer set of options for dealing with deltas:
from dateutil.relativedelta import relativedelta
adate + relativedelta(months=1)
relativedelta
knows about leap years, month lengths, etc. and will do the right thing when adding a month to, say, January 30th (you end up with February 28th or 29th, it won't cross month boundaries).
adding a day date in time.struct_time object
Can you use datetime.datetime
instead?
>>> from datetime import datetime, timedelta
>>> d = datetime.today()
>>> d
datetime.datetime(2018, 2, 22, 16, 25, 1, 596038)
>>> tomorrow = (d + timedelta(days=1))
>>> tomorrow
datetime.datetime(2018, 2, 23, 16, 25, 1, 596038)
>>> d.day, tomorrow.day
(22, 23)
Python datetime.datetime from time.structtime difference
Actually, as explained in the documentation for datetime.fromtimestamp
, it converts to local time by default:
Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive
The 1 hour difference can then be explained by the field tm_isdst=0
tells it to not use daylight savings (despite your local time zone using it).
To see this more clearly, we construct two test cases
import time, datetime
# this is how your time object was constructed before
tm_isdst = 0
t = time.mktime((2015, 8, 1, 20, 28, 33, 5, 213, tm_isdst))
print("Old conversion: {0}".format(datetime.datetime.fromtimestamp(t)))
# this is what happens if you let mktime "divine" a time zone
tm_isdst = -1
t = time.mktime((2015, 8, 1, 20, 28, 33, 5, 213, tm_isdst))
print("New conversion: {0}".format(datetime.datetime.fromtimestamp(t)))
The output of this is as follows:
Old conversion: 2015-08-01 21:28:33
New conversion: 2015-08-01 20:28:33
The problem then, you see, is that the structTime
object being passed to your publishParsedToDatetime
has tm_isdst=0
but the time stamp you wanted to parse was for a DST time zone.
As you have already noted in another comment, the proper solution to this is probably to always use UTC in your back-end code, and only do time zone handling when showing the time to the user, or when reading user input.
strptime string to datetime object conversion
Try:-
import time
import datetime
print(time.strftime("%Y-%m-%d %H:%M:%S %w/%j"))
pre_create_date = (datetime.datetime.today() - datetime.timedelta(60)).strftime("%Y-%m-%d %H:%M:%S %w/%j")
print(pre_create_date)
OUTPUT:-
2019-05-30 12:59:27 4/150
2019-03-31 12:59:27 0/090
WORKING:-
The above code first prints out the current Timestamp(the format is the one you asked for). And then outputs the 60 days early Timestamp from current date (today - 60).
Just used strftime()
to get our desired attributes off the current date.
EXPLANATION OF CODES USED IN strftime()
:-
%Y Year with century as a decimal number.
%m Month as a zero-padded decimal number.
%d Day of the month as a zero-padded decimal.
%H Hour (24-hour clock) as a zero-padded decimal number.
%M Minute as a zero-padded decimal number.
%S Second as a zero-padded decimal number.
%w Week number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are considered to be in week 0.
%j Day of the year as a zero-padded decimal number.
NOTE:- After passing the dates via strftime()
the output will be of datatype string
. If you want the output to be a datetime object then use:-
datetimeobj_1 = datetime.datetime.strptime(pre_create_date, "%Y-%m-%d %H:%M:%S %w/%j")
print(type(datetimeobj_1))
OUTPUT:-
<class 'datetime.datetime'>
If you want the output to be a 'time.struct_time' object then use:-
datetimeobj_1 = time.strptime(pre_create_date, "%Y-%m-%d %H:%M:%S %w/%j")
print(type(datetimeobj_1))
OUTPUT:-
<class 'time.struct_time'>
Related Topics
How to Find the Groups of Consecutive Elements in a Numpy Array
Understanding Popen.Communicate
Django: Improperlyconfigured: the Secret_Key Setting Must Not Be Empty
Monitoring Contents of Files/Directories
Python Equivalent of Setinterval()
Tensorflow Read Images with Labels
Valueerror: Could Not Convert String to Float: Id
Fast Replacement of Values in a Numpy Array
Difference Between .String and .Text Beautifulsoup
Dangers of Sys.Setdefaultencoding('Utf-8')
How to Prevent a C Shared Library to Print on Stdout in Python
How to Get an Event Callback When a Tkinter Entry Widget Is Modified
Does Python Have a Bitfield Type
Find Length of Sequences of Identical Values in a Numpy Array (Run Length Encoding)