简体   繁体   中英

changing datetime format from date to date time

I have a list of dates stored as strings. I need to convert them to this format "%Y%m%d %H:%M:%S %Z"

I can not achieve this since the date stored as a string has no time, just the date. eg. 2015-06-12

below is one iteration of the code/idea i tried but failed. any suggestions are greatly appreciated!

d = "2015-06-12"

x = datetime.datetime.strptime(d, "%Y-%m-%d").date()    

x =  datetime.date(x) + datetime.time(10, 23)

print(x)

You can use datetime.replace() :

from datetime import datetime

d = "2015-06-12"
x = datetime.strptime(d, "%Y-%m-%d").replace(hour=10, minute=23)

To print it in desired format you can usedatetime.strftime() :

print(x.strftime("%Y%m%d %H:%M:%S %Z"))

BUT it won't print timezone name (%Z), cause created datetime object has no information about timezone. You can add it manually, by providing time delta between UTC and timezone:

from datetime import datetime, timezone, timedelta

x = datetime.strptime(d, "%Y-%m-%d").replace(hour=10, minute=23,
                                             tzinfo=timezone(timedelta(hours=6), name="CST"))

Or set local timezone:

x = datetime.strptime(d, "%Y-%m-%d").replace(hour=10, minute=23, 
                                             tzinfo=datetime.utcnow().astimezone().tzinfo)

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