简体   繁体   中英

Convert date string to UTC datetime

I returned dates between two given dates:

for date in rrule(DAILY, dtstart = date1, until = date2):
        print date_item.strftime("%Y-%m-%d")

How to convert the date_item eg 2016-01-01 to ISO 8601 format like: 2016-01-01T18:10:18.000Z in python?

I created a sample datetime object like shown below:

from datetime import datetime 
now = datetime.now()
print now
2016-09-21 16:59:18.175038

Here is the output, formatted to your requirement:

print datetime.strftime(now, "%Y-%m-%dT%H:%M:%S.000Z")
'2016-09-21T16:59:18.000Z'

Here is a good site to refer the various options, I personally find it easier to use than Python's official docs: http://strftime.org

You can use strftime to convert date_item in any format as per your requirement.see the below example

current_time = strftime("%Y-%m-%dT%H:%M:%SZ",gmtime())
print(current_time)

Output:

'2016-09-21T11:30:04Z'

so you can use like this:

from time import gmtime,strftime
import datetime
date_item = datetime.datetime.now()
print date_item.strftime("%Y-%m-%dT%H:%M:%SZ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM