Ok, dates in VBA and Excel are somehow complicated, because of some “feature” that Microsoft Excel has introduced, due to compatibility issues. I have already wrote a few articles about these here, and separate one about what day is Friday in the week of a given date here, and how to use NetworkDays with Dateserial in Excel here. Fortunately, this is not the case with Python, where the benevolent dictator would not have allowed it (or at least we all hope so).
The idea of this article is simply to show some code, that will produce well formatted strings from a date, that will save me a few clicks in google, every time I need to implement it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
from datetime import datetime, timedelta # 2022Aug15_222733 my_date = datetime.now().strftime("%Y%b%d_%H%M%S") print(my_date) # 2022_DecemberDec_22__ThursdayThu__010203 my_date = datetime(2022,12,22,1,2,3).strftime("%Y_%B%b_%d__%A%a__%H%M%S") print(my_date) # 2022-12-22 01:02:03 my_date = datetime(2022,12,22,1,2,3) print(my_date) # 2022-12-22 01:02:03.000004 my_date = datetime(2022,12,22,1,2,3,4) print(my_date) # 2024-10-23 22:27:33.059718 my_date = datetime.now() + timedelta(days=800) print(my_date) |
The only thing that is worth mentioning is probably the beautiful application of timedelta, that can solve some possible problems if you might have, when you need to add or remove some time period. The rest is probably self-explanatory.
Enjoy it!